repo
string | commit
string | message
string | diff
string |
---|---|---|---|
hotchpotch/as3rails2u
|
2a8524d299d23351a51fc568d480c29c56970ed8
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@55 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/core/Enumerable.as b/src/com/rails2u/core/Enumerable.as
new file mode 100644
index 0000000..14e31e2
--- /dev/null
+++ b/src/com/rails2u/core/Enumerable.as
@@ -0,0 +1,59 @@
+package com.rails2u.core {
+ public class Enumerable {
+ public static function zip(t:*, ...args):Enumerator {
+ var ary:Array = take(t);
+ var res:Array = [];
+ var num:uint = Math.min.apply(null,
+ [ary.length].concat(args.map(function(e:*, ...a):Number { return e.length })));
+
+ args = args.map(function(e:*, ...a):Array { return take(e, num) });
+ for (var i:uint = 0; i < num; i++) {
+ var r:Array = [ary[i]];
+ for each(var a:Array in args) {
+ r.push(a[i]);
+ }
+ res.push(r);
+ }
+ return new Enumerator(res);
+ }
+
+ public static function cycle(t:*):Enumerator {
+ var ary:Array = take(t);
+ return new Enumerator(ary, iCycle, valReturn(true), valReturn(Infinity));
+ }
+
+ private static function iCycle(e:Enumerator):* {
+ if(! (e._ary.length > e.index)) {
+ e.rewind();
+ }
+ return e._ary[e.index++];
+ }
+
+ private static function valReturn(v:*):Function {
+ return function(...args):* {
+ return v;
+ }
+ }
+
+ public static function take(t:*, maxValue:Number = Infinity):Array {
+ var res:Array = [];
+ try {
+ if (t is Array) {
+ t.forEach(function(e:*, i:int, ...args):void {
+ if (i++ > maxValue) throw new StopIteration;
+ res.push(e);
+ });
+ } else {
+ var i:uint = 0;
+ t.each(function(e:*, ...args):void {
+ if (i++ > maxValue) throw new StopIteration;
+ res.push(e)
+ });
+ }
+ } catch(e:StopIteration) {
+ //
+ }
+ return res;
+ }
+ }
+}
diff --git a/src/com/rails2u/core/Enumerator.as b/src/com/rails2u/core/Enumerator.as
new file mode 100644
index 0000000..dcc8a2b
--- /dev/null
+++ b/src/com/rails2u/core/Enumerator.as
@@ -0,0 +1,99 @@
+package com.rails2u.core {
+ public class Enumerator {
+ internal var iNext:Function;
+ internal var iHasNext:Function;
+ internal var iCount:Function;
+ internal var index:uint = 0;
+ internal var _ary:Array;
+
+ public function Enumerator(
+ _ary:Array = null,
+ iNext:Function = null,
+ iHasNext:Function = null,
+ iCount:Function = null
+ ) {
+ if (_ary)
+ this._ary = _ary.splice(0);
+ if (iNext)
+ this.iNext = iNext;
+ if (iHasNext)
+ this.iHasNext = iHasNext;
+ if (iCount)
+ this.iCount = iCount;
+ }
+
+ public function rewind():void {
+ index = 0;
+ }
+
+ public function get length():Number {
+ if (iCount is Function) {
+ return iCount(this);
+ } else {
+ return _ary.length;
+ }
+ }
+
+ public function get count():Number {
+ return length;
+ }
+
+ public function each(f:Function):void {
+ var iTemp:uint = index;
+ index = 0;
+ try {
+ while(hasNext()) f(next());
+ } finally {
+ index = iTemp;
+ }
+ }
+
+ public function next():* {
+ if (!hasNext()) {
+ throw new StopIteration('StopIteration');
+ }
+ if (iNext is Function) {
+ return iNext(this);
+ } else {
+ return _ary[index++];
+ }
+ }
+
+ public function hasNext():Boolean {
+ if (iHasNext is Function) {
+ return iHasNext(this);
+ } else {
+ return _ary.length > index;
+ }
+ }
+
+ public function to_a():Array {
+ var iTemp:uint = index;
+ index = 0;
+ var res:Array = [];
+ while(hasNext()) {
+ res.push(next());
+ }
+ index = iTemp;
+ return res;
+ }
+
+ //rb_define_method(rb_mKernel, "to_enum", obj_to_enum, -1);
+ //rb_define_method(rb_mKernel, "enum_for", obj_to_enum, -1);
+
+ //rb_define_method(rb_mEnumerable, "each_slice", enum_each_slice, 1);
+ //rb_define_method(rb_mEnumerable, "each_cons", enum_each_cons, 1);
+
+ //rb_cEnumerator = rb_define_class_under(rb_mEnumerable, "Enumerator", rb_cObject);
+ //rb_include_module(rb_cEnumerator, rb_mEnumerable);
+
+ //rb_define_alloc_func(rb_cEnumerator, enumerator_allocate);
+ //rb_define_method(rb_cEnumerator, "initialize", enumerator_initialize, -1);
+ //rb_define_method(rb_cEnumerator, "initialize_copy", enumerator_init_copy, 1);
+ //rb_define_method(rb_cEnumerator, "each", enumerator_each, 0);
+ //rb_define_method(rb_cEnumerator, "with_index", enumerator_with_index, 0);
+ //rb_define_method(rb_cEnumerator, "to_splat", enumerator_to_splat, 0);
+ //rb_define_method(rb_cEnumerator, "next", enumerator_next, 0);
+ //rb_define_method(rb_cEnumerator, "rewind", enumerator_rewind, 0);
+ }
+}
diff --git a/src/com/rails2u/core/StopIteration.as b/src/com/rails2u/core/StopIteration.as
new file mode 100644
index 0000000..283fb65
--- /dev/null
+++ b/src/com/rails2u/core/StopIteration.as
@@ -0,0 +1,7 @@
+package com.rails2u.core {
+ public class StopIteration extends Error {
+ public function StopIteration(s:String = '', id:int = 0) {
+ super(s, id);
+ }
+ }
+}
diff --git a/src/com/rails2u/layout/Cell.as b/src/com/rails2u/layout/Cell.as
index a581eab..97cd412 100644
--- a/src/com/rails2u/layout/Cell.as
+++ b/src/com/rails2u/layout/Cell.as
@@ -1,107 +1,108 @@
package com.rails2u.layout {
import flash.events.EventDispatcher;
import flash.display.DisplayObject;
public class Cell {
protected var _rowIndex:uint;
protected var _columnIndex:uint;
protected var _layout:GridLayout;
public var data:Object;
public function Cell(layout:GridLayout, rowIndex:uint, columnIndex:uint) {
+ data = {};
this._layout = layout;
this._rowIndex = rowIndex;
this._columnIndex = columnIndex;
}
protected var _content:DisplayObject;
public function get content():DisplayObject {
return _content;
}
public function set content(o:DisplayObject):void {
_layout.container.addChild(o);
o.x = xValue;
o.y = yValue;
_content = o;
}
public function get xValue():Number {
if (_layout.align == GridLayout.ALIGN_CENTER) {
return (rowIndex + 0.5) * width;
//} else if (_layout.align == GridLayout.ALIGN_TOP_LEFT) {
} else {
return rowIndex * width;
}
}
public function get yValue():Number {
if (_layout.align == GridLayout.ALIGN_CENTER) {
return (columnIndex + 0.5) * height;
//} else if (_layout.align == GridLayout.ALIGN_TOP_LEFT) {
} else {
return columnIndex * height;
}
}
public function get width():Number {
return _layout.cellWidth;
}
public function get height():Number {
return _layout.cellHeight;
}
public function get topLeft():Cell {
return _layout.topLeft(rowIndex, columnIndex);
}
public function get top():Cell {
return _layout.top(rowIndex, columnIndex);
}
public function get topRight():Cell {
return _layout.topRight(rowIndex, columnIndex);
}
public function get left():Cell {
return _layout.left(rowIndex, columnIndex);
}
public function get right():Cell {
return _layout.right(rowIndex, columnIndex);
}
public function get bottomLeft():Cell {
return _layout.bottomLeft(rowIndex, columnIndex);
}
public function get bottom():Cell {
return _layout.bottom(rowIndex, columnIndex);
}
public function get bottomRight():Cell {
return _layout.bottomRight(rowIndex, columnIndex);
}
public function get layout():GridLayout {
return _layout;
}
public function set layout(o:GridLayout):void {
_layout = o;
}
public function get rowIndex():Number {
return _rowIndex;
}
public function get columnIndex():Number {
return _columnIndex;
}
public function toString():String {
return 'Cell: [' + rowIndex + ', ' + columnIndex + ']';
}
}
}
diff --git a/src/com/rails2u/layout/GridLayout.as b/src/com/rails2u/layout/GridLayout.as
index 17f575a..d5b07e7 100644
--- a/src/com/rails2u/layout/GridLayout.as
+++ b/src/com/rails2u/layout/GridLayout.as
@@ -1,238 +1,246 @@
package com.rails2u.layout {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.display.DisplayObject;
public class GridLayout {
protected var _rowCount:uint;
protected var _columnCount:uint;
protected var _cellHeight:Number;
protected var _cellWidth:Number;
protected var _container:Sprite;
protected var _cells:Array;
public static const ALIGN_CENTER:String = 'center';
public static const ALIGN_TOP_LEFT:String = 'top_left';
public var align:String = ALIGN_CENTER; // center or top_left
public function GridLayout(container:Sprite, rowCount:uint, columnCount:uint, cellWidth:Number, cellHeight:Number) {
_container = container;
_rowCount = rowCount;
_columnCount = columnCount;
_cellHeight = cellHeight;
_cellWidth = cellWidth;
_cells = [];
for (var rowIndex:uint = 0; rowIndex < _rowCount; rowIndex++) {
var r:Array = [];
for (var columnIndex:uint = 0; columnIndex < _columnCount; columnIndex++) {
r.push(new Cell(this, rowIndex, columnIndex));
}
_cells.push(r);
}
}
public static function newFromSize(
container:Sprite, width:Number, height:Number, cellWidth:Number, cellHeight:Number):GridLayout
{
return new GridLayout(
container,
Math.floor(width / cellWidth),
Math.floor(height / cellHeight),
cellWidth,
cellHeight
);
}
public function get container():Sprite {
return _container;
}
public function get rowCount():uint {
return _rowCount;
}
public function get columnCount():uint {
return _columnCount;
}
public function get cellHeight():Number {
return _cellHeight;
}
public function get cellWidth():Number {
return _cellWidth;
}
/*
public function moveTo(r:uint, c:uint, toR:uint, toC:uint, setPosition:Boolean = true):Boolean {
if (check(r, c) && !check(toR, toC)) {
var o:DisplayObject = remove(r, c);
//setObject(toR, toC, o, setPosition);
return true;
} else {
return false;
}
}
*/
public function remove(r:uint, c:uint):DisplayObject {
var o:DisplayObject = cell(r, c).content;
_cells[r][c] = null;
if (o) container.removeChild(o);
return o;
}
public function topLeft(r:uint, c:uint):Cell {
return getCellIgnoreError(r - 1, c - 1);
}
public function top(r:uint, c:uint):Cell {
return getCellIgnoreError(r, c - 1);
}
public function topRight(r:uint, c:uint):Cell {
return getCellIgnoreError(r + 1, c - 1);
}
public function left(r:uint, c:uint):Cell {
return getCellIgnoreError(r - 1, c);
}
public function right(r:uint, c:uint):Cell {
return getCellIgnoreError(r + 1, c);
}
public function bottomLeft(r:uint, c:uint):Cell {
return getCellIgnoreError(r - 1, c + 1);
}
public function bottom(r:uint, c:uint):Cell {
return getCellIgnoreError(r, c + 1);
}
public function bottomRight(r:uint, c:uint):Cell {
return getCellIgnoreError(r + 1, c + 1);
}
public function check(r:uint, c:uint):Boolean {
if (r > rowCount-1 || c > columnCount-1)
throw new LayoutError('Cell [' + [r,c].toString() + '] is over in layout.');
return !!_cells[r][c];
}
public function cell(r:uint, c:uint):Cell {
return _cells[r][c];
}
+ public function getCellByPosition(xPos:Number, yPos:Number):Cell {
+ if (xPos < 0 || yPos < 0 || xPos > width || yPos > height) {
+ return null;
+ } else {
+ return cell( Math.floor(xPos / cellWidth), Math.floor(yPos / cellHeight));
+ }
+ }
+
public function cells(hasDisplayObjectOnly:Boolean = false):Array {
var res:Array = [];
for (var r:uint = 0; r < rowCount; r++) {
res = res.concat(row(r, hasDisplayObjectOnly));
}
return res;
}
public function getCellIgnoreError(r:uint, c:uint):Cell {
if (r > rowCount-1 || c > columnCount-1) return null;
return _cells[r][c];
}
public function get width():Number {
return (_rowCount) * _cellWidth;
}
public function get height():Number {
return (_columnCount) * _cellHeight;
}
public function row(r:uint, hasDisplayObjectOnly:Boolean = false):Array {
if (r > rowCount-1)
throw new LayoutError('Row [' + r + '] is over in layout.');
var res:Array = [];
for (var c:uint = 0; c < columnCount; c++) {
if (hasDisplayObjectOnly) {
if (_cells[r][c].content)
res.push(_cells[r][c]);
} else {
res.push(_cells[r][c]);
}
}
return res;
}
public function column(c:uint, hasDisplayObjectOnly:Boolean = false):Array {
if (c > columnCount-1)
throw new LayoutError('Column [' + c + '] is over in layout.');
var res:Array = [];
for (var r:uint = 0; r < rowCount; r++) {
if (hasDisplayObjectOnly) {
if (_cells[r][c].content)
res.push(_cells[r][c]);
} else {
res.push(_cells[r][c]);
}
}
return res;
}
/*
public function createObjects(f:Function):void {
var xPoint:Number;
var yPoint:Number;
for (var x:uint = 0; x < _rowCount; x++) {
xPoint = x * cellWidth;
for (var y:uint = 0; y < _columnCount; y++) {
yPoint = y * cellHeight;
setObject(x, y, f.call(null, x, y, xPoint, yPoint), false);
}
}
}
*/
public function drawLines(setGraphics:Function = null):void {
var g:Graphics = container.graphics;
setGraphics ||= function(g:Graphics):void {
g.lineStyle(0, 0x999999);
}
setGraphics(g);
var xPoint:Number;
var yPoint:Number;
for (var x:uint = 0; x <= _rowCount; x++) {
xPoint = x * cellWidth;
g.moveTo(xPoint, 0);
g.lineTo(xPoint, height);
for (var y:uint = 0; y <= _columnCount; y++) {
yPoint = y * cellHeight;
g.moveTo(0, yPoint);
g.lineTo(width, yPoint);
}
}
}
public function showPoints(size:Number = 5, setGraphics:Function = null):void {
var g:Graphics = container.graphics;
setGraphics ||= function(g:Graphics):void {
g.lineStyle(0, 0x999999);
}
setGraphics(g);
var xPoint:Number;
var yPoint:Number;
for (var x:uint = 0; x < _rowCount; x++) {
xPoint = (x + (align == ALIGN_CENTER ? 0.5 : 0)) * cellWidth;
for (var y:uint = 0; y < _columnCount; y++) {
yPoint = (y + (align == ALIGN_CENTER ? 0.5 : 0)) * cellHeight;
g.moveTo(-size + xPoint, yPoint);
g.lineTo(size + xPoint, yPoint);
g.moveTo(xPoint, -size + yPoint);
g.lineTo(xPoint, size + yPoint);
}
}
}
}
}
diff --git a/tests/TestEnum.as b/tests/TestEnum.as
new file mode 100644
index 0000000..68b5614
--- /dev/null
+++ b/tests/TestEnum.as
@@ -0,0 +1,55 @@
+package
+{
+ import flash.display.Sprite;
+ import com.rails2u.core.*;
+
+ public class TestEnum extends Sprite
+ {
+ public var res:String = '';
+
+ public function TestEnum() {
+ var e1:Enumerator = new Enumerator([1,2,3]);
+ equ(e1.next(), 1);
+ equ(e1.hasNext(), true);
+ equ(e1.next(), 2);
+ equ(e1.hasNext(), true);
+ equ(e1.next(), 3);
+ equ(e1.hasNext(), false);
+ equ(e1.count, 3);
+
+ equ([[1,4],[2,5],[3,6]], Enumerable.zip([1,2,3], [4,5,6]).to_a(), true);
+ equ([[1,4,7],[2,5,8],[3,6,9]], Enumerable.zip([1,2,3], [4,5,6], [7,8,9]).to_a(), true);
+ equ([[1,4,7],[2,5,8],[3,6,9]], Enumerable.zip([1,2,3], [4,5,6,10], [7,8,9]).to_a(), true);
+
+ var cycle:Enumerator = Enumerable.cycle([1,2,3]);
+ equ(cycle.next(), 1);
+ equ(cycle.next(), 2);
+ equ(cycle.next(), 3);
+ equ(cycle.next(), 1);
+ equ(cycle.next(), 2);
+ equ(cycle.next(), 3);
+ equ(cycle.next(), 1);
+ equ(cycle.count, Infinity);
+ equ([[1,1],[2,2],[3,3],[4,1]], Enumerable.zip([1,2,3,4], cycle).to_a(), true)
+ equ(cycle.next(), 2);
+ showResult();
+ }
+
+ public function showResult():void {
+ log(res);
+ }
+
+ public function equ(a:*, b:*, stringnize:Boolean = false):void {
+ if(stringnize) {
+ a = a.toString();
+ b = b.toString();
+ }
+
+ if (a==b) {
+ res += '.';
+ } else {
+ log('Error:', a, b);
+ }
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
5084f00dc6b0f0d2649229199bed34f17da8b063
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@54 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/layout/Cell.as b/src/com/rails2u/layout/Cell.as
new file mode 100644
index 0000000..a581eab
--- /dev/null
+++ b/src/com/rails2u/layout/Cell.as
@@ -0,0 +1,107 @@
+package com.rails2u.layout {
+ import flash.events.EventDispatcher;
+ import flash.display.DisplayObject;
+
+ public class Cell {
+ protected var _rowIndex:uint;
+ protected var _columnIndex:uint;
+ protected var _layout:GridLayout;
+ public var data:Object;
+
+ public function Cell(layout:GridLayout, rowIndex:uint, columnIndex:uint) {
+ this._layout = layout;
+ this._rowIndex = rowIndex;
+ this._columnIndex = columnIndex;
+ }
+
+ protected var _content:DisplayObject;
+ public function get content():DisplayObject {
+ return _content;
+ }
+
+ public function set content(o:DisplayObject):void {
+ _layout.container.addChild(o);
+ o.x = xValue;
+ o.y = yValue;
+ _content = o;
+ }
+
+ public function get xValue():Number {
+ if (_layout.align == GridLayout.ALIGN_CENTER) {
+ return (rowIndex + 0.5) * width;
+ //} else if (_layout.align == GridLayout.ALIGN_TOP_LEFT) {
+ } else {
+ return rowIndex * width;
+ }
+ }
+
+ public function get yValue():Number {
+ if (_layout.align == GridLayout.ALIGN_CENTER) {
+ return (columnIndex + 0.5) * height;
+ //} else if (_layout.align == GridLayout.ALIGN_TOP_LEFT) {
+ } else {
+ return columnIndex * height;
+ }
+ }
+
+ public function get width():Number {
+ return _layout.cellWidth;
+ }
+
+ public function get height():Number {
+ return _layout.cellHeight;
+ }
+
+ public function get topLeft():Cell {
+ return _layout.topLeft(rowIndex, columnIndex);
+ }
+
+ public function get top():Cell {
+ return _layout.top(rowIndex, columnIndex);
+ }
+
+ public function get topRight():Cell {
+ return _layout.topRight(rowIndex, columnIndex);
+ }
+
+ public function get left():Cell {
+ return _layout.left(rowIndex, columnIndex);
+ }
+
+ public function get right():Cell {
+ return _layout.right(rowIndex, columnIndex);
+ }
+
+ public function get bottomLeft():Cell {
+ return _layout.bottomLeft(rowIndex, columnIndex);
+ }
+
+ public function get bottom():Cell {
+ return _layout.bottom(rowIndex, columnIndex);
+ }
+
+ public function get bottomRight():Cell {
+ return _layout.bottomRight(rowIndex, columnIndex);
+ }
+
+ public function get layout():GridLayout {
+ return _layout;
+ }
+
+ public function set layout(o:GridLayout):void {
+ _layout = o;
+ }
+
+ public function get rowIndex():Number {
+ return _rowIndex;
+ }
+
+ public function get columnIndex():Number {
+ return _columnIndex;
+ }
+
+ public function toString():String {
+ return 'Cell: [' + rowIndex + ', ' + columnIndex + ']';
+ }
+ }
+}
diff --git a/src/com/rails2u/layout/GridLayout.as b/src/com/rails2u/layout/GridLayout.as
index 749c4bd..17f575a 100644
--- a/src/com/rails2u/layout/GridLayout.as
+++ b/src/com/rails2u/layout/GridLayout.as
@@ -1,179 +1,238 @@
package com.rails2u.layout {
import flash.display.Graphics;
import flash.display.Sprite;
import flash.display.DisplayObject;
public class GridLayout {
- protected var _row:uint;
- protected var _column:uint;
- protected var _boxHeight:Number;
- protected var _boxWidth:Number;
- protected var _target:Sprite;
- protected var _boxes:Array;
-
- public function GridLayout(target:Sprite, row:uint, column:uint, boxWidth:Number, boxHeight:Number) {
- _target = target;
- _row = row;
- _column = column;
- _boxHeight = boxHeight;
- _boxWidth = boxWidth;
- _boxes = [];
- _boxes.map(function(...args):* { return new Array(_column); });
-
- for (var x:uint = 0; x < _row; x++) {
+ protected var _rowCount:uint;
+ protected var _columnCount:uint;
+ protected var _cellHeight:Number;
+ protected var _cellWidth:Number;
+ protected var _container:Sprite;
+ protected var _cells:Array;
+ public static const ALIGN_CENTER:String = 'center';
+ public static const ALIGN_TOP_LEFT:String = 'top_left';
+ public var align:String = ALIGN_CENTER; // center or top_left
+
+ public function GridLayout(container:Sprite, rowCount:uint, columnCount:uint, cellWidth:Number, cellHeight:Number) {
+ _container = container;
+ _rowCount = rowCount;
+ _columnCount = columnCount;
+ _cellHeight = cellHeight;
+ _cellWidth = cellWidth;
+ _cells = [];
+
+ for (var rowIndex:uint = 0; rowIndex < _rowCount; rowIndex++) {
var r:Array = [];
- for (var y:uint = 0; y < _column; y++) {
- r.push(null);
+ for (var columnIndex:uint = 0; columnIndex < _columnCount; columnIndex++) {
+ r.push(new Cell(this, rowIndex, columnIndex));
}
- _boxes.push(r);
+ _cells.push(r);
}
}
- public static function fromSize(
- target:Sprite, width:Number, height:Number, boxWidth:Number, boxHeight:Number):GridLayout
+ public static function newFromSize(
+ container:Sprite, width:Number, height:Number, cellWidth:Number, cellHeight:Number):GridLayout
{
return new GridLayout(
- target,
- Math.floor(width / boxWidth),
- Math.floor(width / boxHeight),
- boxHeight,
- boxWidth
+ container,
+ Math.floor(width / cellWidth),
+ Math.floor(height / cellHeight),
+ cellWidth,
+ cellHeight
);
}
- public function get target():Sprite {
- return _target;
+ public function get container():Sprite {
+ return _container;
}
- public function get row():uint {
- return _row;
+ public function get rowCount():uint {
+ return _rowCount;
}
- public function get column():uint {
- return _column;
+ public function get columnCount():uint {
+ return _columnCount;
}
- public function get boxHeight():Number {
- return _boxHeight;
+ public function get cellHeight():Number {
+ return _cellHeight;
}
- public function get boxWidth():Number {
- return _boxWidth;
- }
-
- public function get layoutedObjects():Array {
- return [];
- }
-
- public function push(o:DisplayObject):void {
+ public function get cellWidth():Number {
+ return _cellWidth;
}
+ /*
public function moveTo(r:uint, c:uint, toR:uint, toC:uint, setPosition:Boolean = true):Boolean {
if (check(r, c) && !check(toR, toC)) {
var o:DisplayObject = remove(r, c);
- setObject(toR, toC, o, setPosition);
+ //setObject(toR, toC, o, setPosition);
return true;
} else {
return false;
}
}
+ */
public function remove(r:uint, c:uint):DisplayObject {
- var o:DisplayObject = getObject(r, c);
- _boxes[r][c] = null;
- target.removeChild(o);
+ var o:DisplayObject = cell(r, c).content;
+ _cells[r][c] = null;
+ if (o) container.removeChild(o);
return o;
}
- public function top(r:uint, c:uint):DisplayObject {
- return getObjectIgnoreError(r - 1, c);
+ public function topLeft(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r - 1, c - 1);
}
- public function setObject(
- r:uint, c:uint, o:DisplayObject, setPosition:Boolean = true):DisplayObject {
- check(r, c);
- _boxes[r][c] = o;
- if (setPosition) {
- o.x = r * boxWidth;
- o.y = c * boxHeight;
- }
- target.addChild(o);
- return o;
+ public function top(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r, c - 1);
+ }
+
+ public function topRight(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r + 1, c - 1);
+ }
+
+ public function left(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r - 1, c);
+ }
+
+ public function right(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r + 1, c);
+ }
+
+ public function bottomLeft(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r - 1, c + 1);
+ }
+
+ public function bottom(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r, c + 1);
+ }
+
+ public function bottomRight(r:uint, c:uint):Cell {
+ return getCellIgnoreError(r + 1, c + 1);
}
public function check(r:uint, c:uint):Boolean {
- if (r > row || c > column)
- throw new LayoutError('Position [' + [r,c].toString() + '] is over in layout.');
- return !!_boxes[r][c];
+ if (r > rowCount-1 || c > columnCount-1)
+ throw new LayoutError('Cell [' + [r,c].toString() + '] is over in layout.');
+ return !!_cells[r][c];
}
- public function checkAndError(r:uint, c:uint):void {
- if (!check(r, c)) throw new LayoutError('Position [' + [r,c].toString() + '] is not found.');
+ public function cell(r:uint, c:uint):Cell {
+ return _cells[r][c];
}
- public function getObject(r:uint, c:uint):DisplayObject {
- checkAndError(r, c);
- return _boxes[r][c];
+ public function cells(hasDisplayObjectOnly:Boolean = false):Array {
+ var res:Array = [];
+ for (var r:uint = 0; r < rowCount; r++) {
+ res = res.concat(row(r, hasDisplayObjectOnly));
+ }
+ return res;
}
- public function getObjectIgnoreError(r:uint, c:uint):DisplayObject {
- return _boxes[r][c];
+ public function getCellIgnoreError(r:uint, c:uint):Cell {
+ if (r > rowCount-1 || c > columnCount-1) return null;
+ return _cells[r][c];
}
public function get width():Number {
- return (_row - 1) * _boxWidth;
+ return (_rowCount) * _cellWidth;
}
public function get height():Number {
- return (_column - 1) * _boxHeight;
+ return (_columnCount) * _cellHeight;
}
+ public function row(r:uint, hasDisplayObjectOnly:Boolean = false):Array {
+ if (r > rowCount-1)
+ throw new LayoutError('Row [' + r + '] is over in layout.');
+
+ var res:Array = [];
+ for (var c:uint = 0; c < columnCount; c++) {
+ if (hasDisplayObjectOnly) {
+ if (_cells[r][c].content)
+ res.push(_cells[r][c]);
+ } else {
+ res.push(_cells[r][c]);
+ }
+ }
+ return res;
+ }
+
+ public function column(c:uint, hasDisplayObjectOnly:Boolean = false):Array {
+ if (c > columnCount-1)
+ throw new LayoutError('Column [' + c + '] is over in layout.');
+
+ var res:Array = [];
+ for (var r:uint = 0; r < rowCount; r++) {
+ if (hasDisplayObjectOnly) {
+ if (_cells[r][c].content)
+ res.push(_cells[r][c]);
+ } else {
+ res.push(_cells[r][c]);
+ }
+ }
+ return res;
+ }
+
+ /*
public function createObjects(f:Function):void {
var xPoint:Number;
var yPoint:Number;
- for (var x:uint = 0; x < _row; x++) {
- xPoint = x * boxWidth;
- for (var y:uint = 0; y < _column; y++) {
- yPoint = y * boxHeight;
- log(x,y, xPoint, yPoint);
+ for (var x:uint = 0; x < _rowCount; x++) {
+ xPoint = x * cellWidth;
+ for (var y:uint = 0; y < _columnCount; y++) {
+ yPoint = y * cellHeight;
setObject(x, y, f.call(null, x, y, xPoint, yPoint), false);
}
}
}
+ */
+
+ public function drawLines(setGraphics:Function = null):void {
+ var g:Graphics = container.graphics;
+ setGraphics ||= function(g:Graphics):void {
+ g.lineStyle(0, 0x999999);
+ }
+ setGraphics(g);
- public function each(f:Function, after:Function = null):* {
var xPoint:Number;
var yPoint:Number;
- for (var x:uint = 0; x < _row; x++) {
- xPoint = x * boxWidth;
- for (var y:uint = 0; y < _column; y++) {
- yPoint = y * boxHeight;
- f.call(null, x, y, xPoint, yPoint);
+ for (var x:uint = 0; x <= _rowCount; x++) {
+ xPoint = x * cellWidth;
+ g.moveTo(xPoint, 0);
+ g.lineTo(xPoint, height);
+ for (var y:uint = 0; y <= _columnCount; y++) {
+ yPoint = y * cellHeight;
+ g.moveTo(0, yPoint);
+ g.lineTo(width, yPoint);
}
}
}
public function showPoints(size:Number = 5, setGraphics:Function = null):void {
- var g:Graphics = target.graphics;
+ var g:Graphics = container.graphics;
setGraphics ||= function(g:Graphics):void {
g.lineStyle(0, 0x999999);
}
setGraphics(g);
var xPoint:Number;
var yPoint:Number;
- for (var x:uint = 0; x < _row; x++) {
- xPoint = x * boxWidth;
- for (var y:uint = 0; y < _column; y++) {
- yPoint = y * boxHeight;
+ for (var x:uint = 0; x < _rowCount; x++) {
+ xPoint = (x + (align == ALIGN_CENTER ? 0.5 : 0)) * cellWidth;
+ for (var y:uint = 0; y < _columnCount; y++) {
+ yPoint = (y + (align == ALIGN_CENTER ? 0.5 : 0)) * cellHeight;
g.moveTo(-size + xPoint, yPoint);
g.lineTo(size + xPoint, yPoint);
g.moveTo(xPoint, -size + yPoint);
g.lineTo(xPoint, size + yPoint);
}
}
}
}
}
|
hotchpotch/as3rails2u
|
fbcf197a9c23f10bd2d4ff325cff15ddb08d940a
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@53 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/layout/GridLayout.as b/src/com/rails2u/layout/GridLayout.as
new file mode 100644
index 0000000..749c4bd
--- /dev/null
+++ b/src/com/rails2u/layout/GridLayout.as
@@ -0,0 +1,179 @@
+package com.rails2u.layout {
+ import flash.display.Graphics;
+ import flash.display.Sprite;
+ import flash.display.DisplayObject;
+
+ public class GridLayout {
+ protected var _row:uint;
+ protected var _column:uint;
+ protected var _boxHeight:Number;
+ protected var _boxWidth:Number;
+ protected var _target:Sprite;
+ protected var _boxes:Array;
+
+ public function GridLayout(target:Sprite, row:uint, column:uint, boxWidth:Number, boxHeight:Number) {
+ _target = target;
+ _row = row;
+ _column = column;
+ _boxHeight = boxHeight;
+ _boxWidth = boxWidth;
+ _boxes = [];
+ _boxes.map(function(...args):* { return new Array(_column); });
+
+ for (var x:uint = 0; x < _row; x++) {
+ var r:Array = [];
+ for (var y:uint = 0; y < _column; y++) {
+ r.push(null);
+ }
+ _boxes.push(r);
+ }
+ }
+
+ public static function fromSize(
+ target:Sprite, width:Number, height:Number, boxWidth:Number, boxHeight:Number):GridLayout
+ {
+ return new GridLayout(
+ target,
+ Math.floor(width / boxWidth),
+ Math.floor(width / boxHeight),
+ boxHeight,
+ boxWidth
+ );
+ }
+
+ public function get target():Sprite {
+ return _target;
+ }
+
+ public function get row():uint {
+ return _row;
+ }
+
+ public function get column():uint {
+ return _column;
+ }
+
+ public function get boxHeight():Number {
+ return _boxHeight;
+ }
+
+ public function get boxWidth():Number {
+ return _boxWidth;
+ }
+
+ public function get layoutedObjects():Array {
+ return [];
+ }
+
+ public function push(o:DisplayObject):void {
+ }
+
+ public function moveTo(r:uint, c:uint, toR:uint, toC:uint, setPosition:Boolean = true):Boolean {
+ if (check(r, c) && !check(toR, toC)) {
+ var o:DisplayObject = remove(r, c);
+ setObject(toR, toC, o, setPosition);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public function remove(r:uint, c:uint):DisplayObject {
+ var o:DisplayObject = getObject(r, c);
+ _boxes[r][c] = null;
+ target.removeChild(o);
+ return o;
+ }
+
+ public function top(r:uint, c:uint):DisplayObject {
+ return getObjectIgnoreError(r - 1, c);
+ }
+
+ public function setObject(
+ r:uint, c:uint, o:DisplayObject, setPosition:Boolean = true):DisplayObject {
+ check(r, c);
+ _boxes[r][c] = o;
+ if (setPosition) {
+ o.x = r * boxWidth;
+ o.y = c * boxHeight;
+ }
+ target.addChild(o);
+ return o;
+ }
+
+ public function check(r:uint, c:uint):Boolean {
+ if (r > row || c > column)
+ throw new LayoutError('Position [' + [r,c].toString() + '] is over in layout.');
+ return !!_boxes[r][c];
+ }
+
+ public function checkAndError(r:uint, c:uint):void {
+ if (!check(r, c)) throw new LayoutError('Position [' + [r,c].toString() + '] is not found.');
+ }
+
+ public function getObject(r:uint, c:uint):DisplayObject {
+ checkAndError(r, c);
+ return _boxes[r][c];
+ }
+
+ public function getObjectIgnoreError(r:uint, c:uint):DisplayObject {
+ return _boxes[r][c];
+ }
+
+ public function get width():Number {
+ return (_row - 1) * _boxWidth;
+ }
+
+ public function get height():Number {
+ return (_column - 1) * _boxHeight;
+ }
+
+ public function createObjects(f:Function):void {
+ var xPoint:Number;
+ var yPoint:Number;
+ for (var x:uint = 0; x < _row; x++) {
+ xPoint = x * boxWidth;
+ for (var y:uint = 0; y < _column; y++) {
+ yPoint = y * boxHeight;
+ log(x,y, xPoint, yPoint);
+ setObject(x, y, f.call(null, x, y, xPoint, yPoint), false);
+ }
+ }
+ }
+
+ public function each(f:Function, after:Function = null):* {
+ var xPoint:Number;
+ var yPoint:Number;
+ for (var x:uint = 0; x < _row; x++) {
+ xPoint = x * boxWidth;
+ for (var y:uint = 0; y < _column; y++) {
+ yPoint = y * boxHeight;
+ f.call(null, x, y, xPoint, yPoint);
+ }
+ }
+ }
+
+ public function showPoints(size:Number = 5, setGraphics:Function = null):void {
+ var g:Graphics = target.graphics;
+ setGraphics ||= function(g:Graphics):void {
+ g.lineStyle(0, 0x999999);
+ }
+ setGraphics(g);
+
+ var xPoint:Number;
+ var yPoint:Number;
+ for (var x:uint = 0; x < _row; x++) {
+ xPoint = x * boxWidth;
+ for (var y:uint = 0; y < _column; y++) {
+ yPoint = y * boxHeight;
+ g.moveTo(-size + xPoint, yPoint);
+ g.lineTo(size + xPoint, yPoint);
+
+ g.moveTo(xPoint, -size + yPoint);
+ g.lineTo(xPoint, size + yPoint);
+ }
+ }
+ }
+
+ }
+}
diff --git a/src/com/rails2u/layout/LayoutError.as b/src/com/rails2u/layout/LayoutError.as
new file mode 100644
index 0000000..73e7cb6
--- /dev/null
+++ b/src/com/rails2u/layout/LayoutError.as
@@ -0,0 +1,7 @@
+package com.rails2u.layout {
+ public class LayoutError extends Error {
+ public function LayoutError(s:String = '', id:int = 0) {
+ super(s, id);
+ }
+ }
+}
diff --git a/src/com/rails2u/pattern/ShapePattern.as b/src/com/rails2u/pattern/ShapePattern.as
new file mode 100644
index 0000000..a72cf47
--- /dev/null
+++ b/src/com/rails2u/pattern/ShapePattern.as
@@ -0,0 +1,58 @@
+package com.rails2u.pattern {
+ import flash.display.DisplayObjectContainer;
+ import flash.geom.Rectangle;
+ import flash.display.Shape;
+
+ public class ShapePattern {
+ public static function fakeHalftone(
+ t:DisplayObjectContainer,
+ rect:Rectangle,
+ col:uint,
+ padding:Number,
+ xSizes:Array,
+ ySizes:Array,
+ afterShapeFunction:Function = null
+ ):void {
+ padding ||= Math.max.apply(null, [].concat(xSizes || []).concat(ySizes || []));
+ var s:Shape;
+ var xSize:Number;
+ var ySize:Number;
+ var radius:Number;
+
+ for (var x:Number = rect.x + padding / 2; x <= rect.right; x += padding) {
+ if (xSizes) {
+ if (xSizes[0] > xSizes[1]) {
+ xSize = xSizes[0] - (x - rect.x) / rect.width * (xSizes[0] - xSizes[1]);
+ } else {
+ xSize = xSizes[0] + (x - rect.x) / rect.width * (xSizes[1] - xSizes[0]);
+ }
+ }
+ for (var y:Number = rect.y + padding / 2; y <= rect.bottom; y += padding) {
+ if (ySizes) {
+ if (ySizes[0] > ySizes[1]) {
+ ySize = ySizes[0] - (y - rect.y) / rect.height * (ySizes[0] - ySizes[1]);
+ } else {
+ ySize = ySizes[0] + (y - rect.y) / rect.height * (ySizes[1] - ySizes[0]);
+ }
+ }
+
+ if (isNaN(xSize) || isNaN(ySize)) {
+ radius = xSize || ySize;
+ } else {
+ radius = (xSize + ySize) / 2;
+ }
+
+ s = new Shape();
+ s.graphics.beginFill(col);
+ s.graphics.drawCircle(0, 0, radius / 2);
+ s.graphics.endFill();
+ s.x = x;
+ s.y = y;
+ t.addChild(s);
+ if (afterShapeFunction is Function) afterShapeFunction(s);
+ }
+ }
+ }
+ }
+}
+
diff --git a/src/com/rails2u/utils/MathUtil.as b/src/com/rails2u/utils/MathUtil.as
index 5e0b321..4fcf705 100644
--- a/src/com/rails2u/utils/MathUtil.as
+++ b/src/com/rails2u/utils/MathUtil.as
@@ -1,90 +1,90 @@
package com.rails2u.utils
{
public class MathUtil
{
public static function randomPlusMinus(val:Number = 1):Number {
if (randomBoolean() ) {
return val;
} else {
return val * -1;
}
}
/*
* randomBoolean(-100, 100); // retun value is between -100 and 100;
*/
public static function randomBetween(s:Number, e:Number = 0):Number {
return s + (e - s) * Math.random();
}
/*
* randomBetween(); // return value is true or false.
*/
public static function randomBoolean():Boolean {
return (Math.round(Math.random()) == 1) ? true : false;
}
/*
* randomPickup(1,2,3,4); // return value is 1 or 2 or 3 or 4
*/
- public static function randomPickup(... args):Object {
+ public static function randomPickup(... args):* {
var len:uint = args.length;
if (len == 1) {
return args[0];
} else {
return args[Math.round(Math.random() * (len - 1))];
}
}
/*
* var cycleABC = MathUtil.cycle('a', 'b', 'c');
* cycleABC(); // 'a'
* cycleABC(); // 'b'
* cycleABC(); // 'c'
* cycleABC(); // 'a'
* cycleABC(); // 'b'
*/
public static function cycle(... args):Function {
var len:uint = args.length;
var i:uint = 0;
if (len == 1) {
return function():Object {
return args[0];
}
} else {
return function():Object {
var res:Object = args[i];
i++;
if (i >= len) i = 0;
return res;
};
}
}
public static function bezier3(t:Number, x0:Number, x1:Number, x2:Number, x3:Number):Number {
return x0 * Math.pow(1-t, 3) + 3 * x1 * t *Math.pow(1-t, 2) + 3 * x2 * Math.pow(t, 2) * 1-t + x3 * Math.pow(t, 3);
}
public static function bezierN(t:Number, points:Array):Number {
var res:Number = 0;
var len:uint = points.length;
var tm:Number = 1 - t;
for (var i:uint=0; i < len;i++) {
var pos:Number = points[i];
var tmp:Number = 1.0;
var a:Number = len - 1;
var b:Number = i;
var c:Number = a - b;
while (a > 1) {
if(a > 1) tmp *= a; a -= 1;
if(b > 1) tmp /= b; b -= 1;
if(c > 1) tmp /= c; c -= 1;
}
tmp *= Math.pow(t, i) * Math.pow(tm, len -1 -i);
res += tmp * pos;
}
return res;
}
}
}
|
hotchpotch/as3rails2u
|
406beecd9429799303eb6da96bfa8f5426518b42
|
add SpringEngine
|
diff --git a/src/com/rails2u/engine/Spring.as b/src/com/rails2u/engine/Spring.as
new file mode 100644
index 0000000..20e4e5a
--- /dev/null
+++ b/src/com/rails2u/engine/Spring.as
@@ -0,0 +1,82 @@
+package com.rails2u.engine {
+ import flash.display.DisplayObject;
+ import flash.utils.Dictionary;
+ import flash.events.EventDispatcher;
+
+ public class Spring extends EventDispatcher {
+ public var target:DisplayObject;
+ public var vx:Number = 0;
+ public var vy:Number = 0;
+ public var defaultNodeLength:Number;
+ protected var _nodes:Array = [];
+ public var nodesLength:Dictionary = new Dictionary();
+
+ public function Spring(target:DisplayObject) {
+ this.target = target;
+ }
+
+ public function addNode(node:Spring, len:Number = NaN):Spring {
+ if (hasNode(node) || node == this)
+ return undefined;
+
+ _nodes.push(node);
+ if (!isNaN(len)) {
+ setNodeLength(node, len);
+ } else if (!isNaN(defaultNodeLength)) {
+ setNodeLength(node, defaultNodeLength);
+ }
+ return node;
+ }
+
+ public function removeNode(node:Spring):Spring {
+ if (!hasNode(node))
+ return undefined;
+
+ if(getNodeLength(node))
+ delete nodesLength[node];
+ _nodes.splice(_nodes.indexOf(node), 1);
+ return node;
+ }
+
+ public function hasNode(node:Spring):Boolean {
+ return _nodes.indexOf(node) == -1 ? false : true;
+ }
+
+ public function refNode(node:Spring, len:Number = NaN):Spring {
+ if (node == this) return undefined;
+
+ node.addNode(this);
+ if (!isNaN(len)) node.setNodeLength(this, len);
+ return node;
+ }
+
+ public function setNodeLength(node:Spring, len:Number):void {
+ nodesLength[node] = len;
+ }
+
+ public function getNodeLength(node:Spring):Number {
+ return nodesLength[node];
+ }
+
+ public function get nodes():Array {
+ return _nodes;
+ }
+
+ public function get x():Number {
+ return target.x;
+ }
+
+ public function set x(val:Number):void {
+ target.x = val;
+ }
+
+ public function get y():Number {
+ return target.y;
+ }
+
+ public function set y(val:Number):void {
+ target.y = val;
+ }
+ }
+}
+
diff --git a/src/com/rails2u/engine/SpringEngine.as b/src/com/rails2u/engine/SpringEngine.as
new file mode 100644
index 0000000..f31ca9b
--- /dev/null
+++ b/src/com/rails2u/engine/SpringEngine.as
@@ -0,0 +1,143 @@
+package com.rails2u.engine {
+ import flash.display.DisplayObjectContainer;
+ import flash.display.DisplayObject;
+ import flash.events.Event;
+ import flash.display.Graphics;
+ import flash.display.Sprite;
+ import flash.events.MouseEvent;
+ import flash.events.EventDispatcher;
+ import flash.geom.Rectangle;
+
+ public class SpringEngine extends EventDispatcher {
+ protected var _springs:Array;
+ public var target:Sprite;
+ public var vSpring:Number = 0.1;
+ public var friction:Number = 0.95;
+ public var drawLine:Boolean = true;
+ public var defaultNodeLength:Number;
+ public var setGraphics:Function = function(g:Graphics):void {
+ g.lineStyle(0.9,0xEEEEEE);
+ };
+ public var surface:Rectangle;
+
+ public function SpringEngine(target:Sprite) {
+ this.target = target;
+ _springs = [];
+ }
+
+ public function get springs():Array {
+ return _springs;
+ }
+
+ public function addSpring(spring:Spring):void {
+ if (hasSpring(spring))
+ return;
+ target.addChild(spring.target);
+ if (isNaN(spring.defaultNodeLength) && !isNaN(defaultNodeLength)) {
+ spring.defaultNodeLength = defaultNodeLength;
+ }
+ _springs.push(spring);
+ dispatchEvent(new Event(Event.ADDED));
+ }
+
+ public function removeSpring(spring:Spring):void {
+ if (!hasSpring(spring))
+ return;
+ target.removeChild(spring.target);
+ _springs.splice(_springs.indexOf(spring), 1);
+ dispatchEvent(new Event(Event.REMOVED));
+ }
+
+ public function hasSpring(spring:Spring):Boolean {
+ return _springs.indexOf(spring) == -1 ? false : true;
+ }
+
+ public function addDisplayObject(d:DisplayObject):Spring {
+ for each(var s:Spring in _springs) {
+ if (s.target == d) return s;
+ }
+ var spring:Spring = new Spring(d);
+ addSpring(spring);
+ return spring;
+ }
+
+ public function start():void {
+ target.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
+ }
+
+ public function stop():void {
+ target.removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
+ }
+
+ public function get graphics():Graphics {
+ return target.graphics;
+ }
+
+ protected function mouseUpHandler(e:MouseEvent):void {
+ e.target.stopDrag();
+ }
+
+ protected function setVelocity(spring:Spring, node:Spring):void {
+ var dx:Number, dy:Number, nodeLen:Number;
+ if (spring.getNodeLength(node)) {
+ dx = spring.x - node.x;
+ dy = spring.y - node.y;
+ nodeLen = spring.getNodeLength(node);
+ var angle:Number = Math.atan2(dy, dx);
+ var targetX:Number = node.x + Math.cos(angle) * nodeLen;
+ var targetY:Number = node.y + Math.sin(angle) * nodeLen;
+ spring.vx += (targetX - spring.x) * vSpring;
+ spring.vy += (targetY - spring.y) * vSpring;
+ } else {
+ dx = node.x - spring.x;
+ dy = node.y - spring.y;
+ spring.vx += dx * vSpring;
+ spring.vy += dy * vSpring;
+ }
+ spring.vx *= friction;
+ spring.vy *= friction;
+ }
+
+ protected function boundSurface(surfaceRectangle:Rectangle, spring:Spring):void {
+ if (spring.x < 0 || (spring.x + spring.target.width) > surfaceRectangle.width) {
+ spring.vx *= -1;
+ }
+ if (spring.y < 0 || (spring.y + spring.target.height) > surfaceRectangle.height) {
+ spring.vy *= -1;
+ }
+ }
+
+ protected function enterFrameHandler(e:Event):void {
+ if (drawLine) {
+ graphics.clear();
+ setGraphics(graphics);
+ }
+
+ var nodes:Array, node:Spring;
+ for each(var spring:Spring in _springs) {
+ nodes = spring.nodes;
+ if (nodes.length) {
+ for (var i:uint = 0; i < nodes.length; i++) {
+ node = nodes[i];
+ setVelocity(spring, node);
+ }
+
+ spring.x += spring.vx;
+ spring.y += spring.vy;
+
+ if (surface)
+ boundSurface(surface, spring);
+
+ if (drawLine) {
+ for (i = 0; i < nodes.length; i++) {
+ graphics.moveTo(spring.x, spring.y);
+ graphics.lineTo(nodes[i].x, nodes[i].y);
+ }
+ }
+ spring.dispatchEvent(new Event(Event.CHANGE));
+ }
+ }
+ }
+
+ }
+}
|
hotchpotch/as3rails2u
|
ea04ccd28c9df09c5ce16f47a4b036fab4e36111
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@51 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/bridge/ExportJS.as b/src/com/rails2u/bridge/ExportJS.as
new file mode 100644
index 0000000..14c2528
--- /dev/null
+++ b/src/com/rails2u/bridge/ExportJS.as
@@ -0,0 +1,194 @@
+package com.rails2u.bridge {
+ import flash.errors.IllegalOperationError;
+ import flash.external.ExternalInterface;
+ import flash.utils.ByteArray;
+ import flash.utils.getQualifiedClassName;
+ import flash.utils.Dictionary;
+ import flash.utils.describeType;
+
+ public class ExportJS {
+ private static var inited:Boolean = false;
+ private static var readOnlyObjectCache:Object;
+ public static var objects:Object;
+ public static var dict:Dictionary;
+
+ public static function reloadObject(jsName:String):void {
+ export(objects[jsName], jsName);
+ ExternalInterface.call('console.info', 'reloaded: ' + jsName);
+ }
+
+ public static function getASObject(jsName:String):* {
+ return objects[jsName];
+ }
+
+ public static function getJSName(targetObject:*):* {
+ return dict[targetObject];
+ }
+
+ private static var cNum:uint = 0;
+ private static function anonCounter():uint {
+ return cNum++;
+ }
+
+ public static function export(targetObject:*, jsName:String = undefined):String {
+ init();
+
+ if (dict[targetObject])
+ jsName = dict[targetObject];
+
+ if (!jsName) jsName = '__as3__.' + anonCounter();
+
+ var b:ByteArray = new ByteArray();
+ b.writeObject(targetObject);
+ b.position = 0;
+ var obj:Object = b.readObject();
+
+ //var readOnlyObject:Object = getReadOnlyObject(targetObject);
+
+ // custom for Sprite/Shape
+ if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
+ obj.graphics = {};
+
+ objects[jsName] = targetObject;
+ dict[targetObject] = jsName;
+ ExternalInterface.call(<><![CDATA[
+ (function(target, objectID, jsName, klassName) {
+ try {
+ var swfObject = document.getElementsByName(objectID)[0];
+
+ var defineAttr = function(obj, parentProperties) {
+ var tmp = {};
+ for (var i in obj) {
+ if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
+ var pp = parentProperties.slice();
+ pp.push(i);
+ defineAttr(obj[i], pp);
+ continue;
+ }
+ tmp[i] = obj[i];
+ obj.__defineGetter__(i,
+ (function(attrName) {
+ return function() {
+ return this.__tmpProperties__[attrName]
+ }
+ })(i)
+ );
+ obj.__defineSetter__(i,
+ (function(attrName) {
+ return function(val) {
+ if (swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val)) {
+ return this.__tmpProperties__[attrName] = val;
+ } else {
+ return this.__tmpProperties__[attrName];
+ }
+ }
+ })(i)
+ );
+ }
+ obj.__noSuchMethod__ = function(attrName, args) {
+ swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
+ }
+ obj.__tmpProperties__ = tmp;
+ }
+ defineAttr(target, []);
+
+ target.__reload = function() { return swfObject.reloadObject(jsName) };
+ if (!target.hasOwnProperty('reload')) target.reload = target.__reload;
+
+ target.toString = function() { return klassName };
+ var chainProperties = jsName.split('.');
+ var windowTarget = window;
+ while (chainProperties.length > 1) {
+ var prop = chainProperties.shift();
+ if (typeof windowTarget[prop] == 'undefined')
+ windowTarget[prop] = {};
+ windowTarget = windowTarget[prop];
+ }
+ windowTarget[chainProperties.shift()] = target;
+ } catch(e) {
+ console.error(e.message, jsName);
+ }
+ ;})
+ ]]></>.toString(),
+ obj,
+ ExternalInterface.objectID,
+ jsName,
+ getQualifiedClassName(targetObject)
+ );
+ return jsName;
+ }
+
+ private static function init():void {
+ if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
+ if (inited) return;
+
+ objects = {};
+ dict = new Dictionary();
+ readOnlyObjectCache = {};
+ ExternalInterface.addCallback('updateProperty', updateProperty);
+ ExternalInterface.addCallback('callMethod', callMethod);
+ ExternalInterface.addCallback('reloadObject', reloadObject);
+ inited = true;
+ }
+
+ private static function updateProperty(jsName:String, chainProperties:Array, value:Object):Boolean {
+ var obj:Object = objects[jsName];
+ while (chainProperties.length > 1) {
+ var prop:String = chainProperties.shift();
+ obj = obj[prop];
+ }
+ try {
+ obj[chainProperties.shift()] = value;
+ } catch(e:Error) {
+ ExternalInterface.call('console.error', e.message);
+ return false;
+ }
+ return true;
+ }
+
+ private static function callMethod(jsName:String, chainProperties:Array, args:Object):* {
+ var obj:Object = objects[jsName];
+ var klassName:String = getQualifiedClassName(obj);
+ var tmp:Array = chainProperties.slice();
+ var prop:String;
+ while (chainProperties.length > 1) {
+ prop = chainProperties.shift();
+ obj = obj[prop];
+ }
+ prop = chainProperties.shift();
+ if(!obj.hasOwnProperty(prop)) {
+ ExternalInterface.call('console.error', jsName + '(' + [klassName].concat(tmp).join('.') + ') is undefined.');
+ return;
+ }
+ var func:Function = obj[prop] as Function;
+
+ try {
+ if (func is Function) {
+ return func.apply(obj, args);
+ } else {
+ ExternalInterface.call('console.error', jsName + '(' + [klassName].concat(tmp).join('.') + ') is not function.');
+ }
+ } catch(e:Error) {
+ ExternalInterface.call('console.error', e.message);
+ }
+ }
+
+ /*
+ private static var readOnlyObjectRegexp:RegExp = new RegExp('name="([^"]+?)" .*access="readonly" .*type="([^"]+?)"');
+ private static function getReadOnlyObject(target:*):Object {
+ var klassName:String = getQualifiedClassName(target);
+ if (!readOnlyObjectCache[klassName]) {
+ // don't use E4X.
+ readOnlyObjectCache[klassName] = {};
+ var xmlLines:Array = describeType(target).toString().split("\n");
+ for each(var line:String in xmlLines) {
+ line.replace(readOnlyObjectRegexp, function(_trash, name, _type, ...trashes):void {
+ readOnlyObjectCache[klassName][name] = _type;
+ });
+ }
+ }
+ return readOnlyObjectCache[klassName];
+ }
+ */
+ }
+}
diff --git a/src/com/rails2u/debug/ExportJS.as b/src/com/rails2u/debug/ExportJS.as
deleted file mode 100644
index 0c8adbb..0000000
--- a/src/com/rails2u/debug/ExportJS.as
+++ /dev/null
@@ -1,126 +0,0 @@
-package com.rails2u.debug {
- import flash.errors.IllegalOperationError;
- import flash.external.ExternalInterface;
- import flash.utils.ByteArray;
- import flash.utils.getQualifiedClassName;
-
- public class ExportJS {
- private static var inited:Boolean = false;
- public static var objects:Object = {};
-
- public static function init():void {
- if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
- if (inited) return;
-
- ExternalInterface.addCallback('updateProperty', updateProperty);
- ExternalInterface.addCallback('callMethod', callMethod);
- ExternalInterface.addCallback('reloadObject', reloadObject);
- inited = true;
- }
-
- public static function updateProperty(jsName:String, chainProperties:Array, value:Object):Boolean {
- var obj:Object = objects[jsName];
- while (chainProperties.length > 1) {
- var prop:String = chainProperties.shift();
- obj = obj[prop];
- }
- try {
- obj[chainProperties.shift()] = value;
- } catch(e:Error) {
- ExternalInterface.call('console.error', e.message);
- return false;
- }
- return true;
- }
-
- public static function callMethod(jsName:String, chainProperties:Array, args:Object):* {
- var obj:Object = objects[jsName];
- while (chainProperties.length > 1) {
- var prop:String = chainProperties.shift();
- obj = obj[prop];
- }
- var func:Function = obj[chainProperties.shift()] as Function;
-
- try {
- if (func is Function) return func.apply(obj, args);
- } catch(e:Error) {
- ExternalInterface.call('console.error', e.message);
- }
- }
-
- public static function reloadObject(jsName:String) {
- export(objects[jsName], jsName);
- ExternalInterface.call('console.info', 'reloaded: ' + jsName);
- }
-
- private static var cNum:uint = 0;
- private static function nonameCounter():uint {
- return cNum++;
- }
-
- public static function export(targetObject:*, jsName:String = undefined):String {
- init();
-
- if (!jsName) jsName = '__swf__' + nonameCounter();
-
- var b:ByteArray = new ByteArray();
- b.writeObject(targetObject);
- b.position = 0;
- var obj:Object = b.readObject();
-
- // custom for Sprite/Shape
- if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
- obj.graphics = {};
-
- objects[jsName] = targetObject;
- ExternalInterface.call(<><![CDATA[
- (function(target, objectID, jsName, klassName) {
- var swfObject = document.getElementsByName(objectID)[0];
-
- var defineAttr = function(obj, parentProperties) {
- var tmp = {};
- for (var i in obj) {
- if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
- var pp = parentProperties.slice();
- pp.push(i);
- defineAttr(obj[i], pp);
- continue;
- }
- tmp[i] = obj[i];
- obj.__defineGetter__(i,
- (function(attrName) {
- return function() {
- return this.__tmpProperties__[attrName]
- }
- })(i)
- );
- obj.__defineSetter__(i,
- (function(attrName) {
- return function(val) {
- if (swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val)) {
- return this.__tmpProperties__[attrName] = val;
- } else {
- return this.__tmpProperties__[attrName];
- }
- }
- })(i)
- );
- }
- obj.__noSuchMethod__ = function(attrName, args) {
- swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
- }
- obj.__tmpProperties__ = tmp;
- }
- defineAttr(target, []);
-
- target.__reload = function() { return swfObject.reloadObject(jsName) };
- if (!target.hasOwnProperty('reload')) target.reload = target.__reload;
-
- target.toString = function() { return klassName };
- window[jsName] = target;
- ;})
- ]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
- return jsName;
- }
- }
-}
diff --git a/src/exportJS.as b/src/exportJS.as
index 8bf21d6..ae93cbf 100644
--- a/src/exportJS.as
+++ b/src/exportJS.as
@@ -1,7 +1,7 @@
package {
- import com.rails2u.debug.ExportJS;
+ import com.rails2u.bridge.ExportJS;
public function exportJS(obj:Object, name:String = undefined):String {
return ExportJS.export(obj, name);
}
}
|
hotchpotch/as3rails2u
|
0309aacbf61955e14c2376c6f600622e238458aa
|
fix sum bugs
|
diff --git a/src/com/rails2u/debug/ExportJS.as b/src/com/rails2u/debug/ExportJS.as
index d1d8cca..0c8adbb 100644
--- a/src/com/rails2u/debug/ExportJS.as
+++ b/src/com/rails2u/debug/ExportJS.as
@@ -1,109 +1,126 @@
package com.rails2u.debug {
import flash.errors.IllegalOperationError;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class ExportJS {
private static var inited:Boolean = false;
public static var objects:Object = {};
public static function init():void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
if (inited) return;
ExternalInterface.addCallback('updateProperty', updateProperty);
ExternalInterface.addCallback('callMethod', callMethod);
ExternalInterface.addCallback('reloadObject', reloadObject);
inited = true;
}
- public static function updateProperty(jsName:String, chainProperties:Array, value:Object):void {
+ public static function updateProperty(jsName:String, chainProperties:Array, value:Object):Boolean {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
- obj[chainProperties.shift()] = value;
+ try {
+ obj[chainProperties.shift()] = value;
+ } catch(e:Error) {
+ ExternalInterface.call('console.error', e.message);
+ return false;
+ }
+ return true;
}
- public static function callMethod(jsName:String, chainProperties:Array, args:Object):void {
+ public static function callMethod(jsName:String, chainProperties:Array, args:Object):* {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
var func:Function = obj[chainProperties.shift()] as Function;
- if (func is Function) func.apply(obj, args);
+
+ try {
+ if (func is Function) return func.apply(obj, args);
+ } catch(e:Error) {
+ ExternalInterface.call('console.error', e.message);
+ }
}
public static function reloadObject(jsName:String) {
export(objects[jsName], jsName);
+ ExternalInterface.call('console.info', 'reloaded: ' + jsName);
}
private static var cNum:uint = 0;
private static function nonameCounter():uint {
return cNum++;
}
public static function export(targetObject:*, jsName:String = undefined):String {
init();
if (!jsName) jsName = '__swf__' + nonameCounter();
var b:ByteArray = new ByteArray();
b.writeObject(targetObject);
b.position = 0;
var obj:Object = b.readObject();
// custom for Sprite/Shape
if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
obj.graphics = {};
objects[jsName] = targetObject;
ExternalInterface.call(<><![CDATA[
(function(target, objectID, jsName, klassName) {
var swfObject = document.getElementsByName(objectID)[0];
var defineAttr = function(obj, parentProperties) {
var tmp = {};
for (var i in obj) {
if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
var pp = parentProperties.slice();
pp.push(i);
defineAttr(obj[i], pp);
continue;
}
tmp[i] = obj[i];
obj.__defineGetter__(i,
(function(attrName) {
return function() {
return this.__tmpProperties__[attrName]
}
})(i)
);
obj.__defineSetter__(i,
(function(attrName) {
return function(val) {
- swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val);
- return this.__tmpProperties__[attrName] = val;
+ if (swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val)) {
+ return this.__tmpProperties__[attrName] = val;
+ } else {
+ return this.__tmpProperties__[attrName];
+ }
}
})(i)
);
}
obj.__noSuchMethod__ = function(attrName, args) {
swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
}
obj.__tmpProperties__ = tmp;
}
defineAttr(target, []);
target.__reload = function() { return swfObject.reloadObject(jsName) };
+ if (!target.hasOwnProperty('reload')) target.reload = target.__reload;
+
target.toString = function() { return klassName };
window[jsName] = target;
;})
]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
return jsName;
}
}
}
|
hotchpotch/as3rails2u
|
2add600c63faf1fda8c7ad771250af7027672392
|
add _reload
|
diff --git a/src/com/rails2u/debug/ExportJS.as b/src/com/rails2u/debug/ExportJS.as
index a9715cc..d1d8cca 100644
--- a/src/com/rails2u/debug/ExportJS.as
+++ b/src/com/rails2u/debug/ExportJS.as
@@ -1,100 +1,109 @@
package com.rails2u.debug {
import flash.errors.IllegalOperationError;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class ExportJS {
private static var inited:Boolean = false;
public static var objects:Object = {};
public static function init():void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
if (inited) return;
ExternalInterface.addCallback('updateProperty', updateProperty);
ExternalInterface.addCallback('callMethod', callMethod);
+ ExternalInterface.addCallback('reloadObject', reloadObject);
inited = true;
}
- public static function updateProperty(target:Object, chainProperties:Array, value:Object):void {
- var obj:Object = objects[target];
+ public static function updateProperty(jsName:String, chainProperties:Array, value:Object):void {
+ var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
obj[chainProperties.shift()] = value;
}
- public static function callMethod(target:Object, chainProperties:Array, args:Object):void {
- var obj:Object = objects[target];
+ public static function callMethod(jsName:String, chainProperties:Array, args:Object):void {
+ var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
var func:Function = obj[chainProperties.shift()] as Function;
if (func is Function) func.apply(obj, args);
}
+
+ public static function reloadObject(jsName:String) {
+ export(objects[jsName], jsName);
+ }
private static var cNum:uint = 0;
private static function nonameCounter():uint {
return cNum++;
}
public static function export(targetObject:*, jsName:String = undefined):String {
init();
- if (!jsName) jsName = '_' + nonameCounter();
+ if (!jsName) jsName = '__swf__' + nonameCounter();
var b:ByteArray = new ByteArray();
b.writeObject(targetObject);
b.position = 0;
var obj:Object = b.readObject();
// custom for Sprite/Shape
if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
obj.graphics = {};
objects[jsName] = targetObject;
ExternalInterface.call(<><![CDATA[
(function(target, objectID, jsName, klassName) {
+ var swfObject = document.getElementsByName(objectID)[0];
+
var defineAttr = function(obj, parentProperties) {
var tmp = {};
for (var i in obj) {
if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
var pp = parentProperties.slice();
pp.push(i);
defineAttr(obj[i], pp);
continue;
}
tmp[i] = obj[i];
obj.__defineGetter__(i,
(function(attrName) {
return function() {
return this.__tmpProperties__[attrName]
}
})(i)
);
obj.__defineSetter__(i,
(function(attrName) {
return function(val) {
- document.getElementsByName(objectID)[0].updateProperty(jsName, [].concat(parentProperties).concat(attrName), val);
+ swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val);
return this.__tmpProperties__[attrName] = val;
}
})(i)
);
}
obj.__noSuchMethod__ = function(attrName, args) {
- document.getElementsByName(objectID)[0].callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
+ swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
}
obj.__tmpProperties__ = tmp;
}
defineAttr(target, []);
+
+ target.__reload = function() { return swfObject.reloadObject(jsName) };
target.toString = function() { return klassName };
window[jsName] = target;
;})
]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
return jsName;
}
}
}
|
hotchpotch/as3rails2u
|
f26b14c0143b350ec6c58c3817c95affad44e4b2
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@48 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/debug/ExportJS.as b/src/com/rails2u/debug/ExportJS.as
new file mode 100644
index 0000000..a9715cc
--- /dev/null
+++ b/src/com/rails2u/debug/ExportJS.as
@@ -0,0 +1,100 @@
+package com.rails2u.debug {
+ import flash.errors.IllegalOperationError;
+ import flash.external.ExternalInterface;
+ import flash.utils.ByteArray;
+ import flash.utils.getQualifiedClassName;
+
+ public class ExportJS {
+ private static var inited:Boolean = false;
+ public static var objects:Object = {};
+
+ public static function init():void {
+ if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
+ if (inited) return;
+
+ ExternalInterface.addCallback('updateProperty', updateProperty);
+ ExternalInterface.addCallback('callMethod', callMethod);
+ inited = true;
+ }
+
+ public static function updateProperty(target:Object, chainProperties:Array, value:Object):void {
+ var obj:Object = objects[target];
+ while (chainProperties.length > 1) {
+ var prop:String = chainProperties.shift();
+ obj = obj[prop];
+ }
+ obj[chainProperties.shift()] = value;
+ }
+
+ public static function callMethod(target:Object, chainProperties:Array, args:Object):void {
+ var obj:Object = objects[target];
+ while (chainProperties.length > 1) {
+ var prop:String = chainProperties.shift();
+ obj = obj[prop];
+ }
+ var func:Function = obj[chainProperties.shift()] as Function;
+ if (func is Function) func.apply(obj, args);
+ }
+
+ private static var cNum:uint = 0;
+ private static function nonameCounter():uint {
+ return cNum++;
+ }
+
+ public static function export(targetObject:*, jsName:String = undefined):String {
+ init();
+
+ if (!jsName) jsName = '_' + nonameCounter();
+
+ var b:ByteArray = new ByteArray();
+ b.writeObject(targetObject);
+ b.position = 0;
+ var obj:Object = b.readObject();
+
+ // custom for Sprite/Shape
+ if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
+ obj.graphics = {};
+
+ objects[jsName] = targetObject;
+ ExternalInterface.call(<><![CDATA[
+ (function(target, objectID, jsName, klassName) {
+ var defineAttr = function(obj, parentProperties) {
+ var tmp = {};
+ for (var i in obj) {
+ if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
+ var pp = parentProperties.slice();
+ pp.push(i);
+ defineAttr(obj[i], pp);
+ continue;
+ }
+ tmp[i] = obj[i];
+ obj.__defineGetter__(i,
+ (function(attrName) {
+ return function() {
+ return this.__tmpProperties__[attrName]
+ }
+ })(i)
+ );
+ obj.__defineSetter__(i,
+ (function(attrName) {
+ return function(val) {
+ document.getElementsByName(objectID)[0].updateProperty(jsName, [].concat(parentProperties).concat(attrName), val);
+ return this.__tmpProperties__[attrName] = val;
+ }
+ })(i)
+ );
+ }
+ obj.__noSuchMethod__ = function(attrName, args) {
+ document.getElementsByName(objectID)[0].callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
+ }
+ obj.__tmpProperties__ = tmp;
+ }
+ defineAttr(target, []);
+ target.toString = function() { return klassName };
+ window[jsName] = target;
+ ;})
+ ]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
+ return jsName;
+ }
+ }
+}
diff --git a/src/exportJS.as b/src/exportJS.as
new file mode 100644
index 0000000..8bf21d6
--- /dev/null
+++ b/src/exportJS.as
@@ -0,0 +1,7 @@
+package {
+ import com.rails2u.debug.ExportJS;
+
+ public function exportJS(obj:Object, name:String = undefined):String {
+ return ExportJS.export(obj, name);
+ }
+}
|
hotchpotch/as3rails2u
|
55d126aa8861dc1e87045940455b666d2f2268cd
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@47 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/log.as b/src/log.as
index 8890d28..21fdbfc 100644
--- a/src/log.as
+++ b/src/log.as
@@ -1,37 +1,41 @@
package {
import flash.external.ExternalInterface;
import com.rails2u.utils.ObjectInspecter;
import flash.utils.getQualifiedClassName;
/**
* log() is Object inspect dump output to trace() and use
* Browser(FireFox, Safari and more) External API console.log.
*
* example
* <listing version="3.0">
* var a:Array = [[1,2,3], [4,[5,6]]];
* var sprite:Sprite = new Sprite;
* log(a, sprite);
* # output
* [[1, 2, 3], [4, [5, 6]]], #<flash.display::Sprite:[object Sprite]>
* </listing>
*/
public function log(... args):String {
var r:String = ObjectInspecter.inspect.apply(null, args);
trace(r)
if (ExternalInterface.available) {
var arg:* = args.length == 1 ? args[0] : args;
- ExternalInterface.call(<><![CDATA[
- (function(obj, klassName) {
- obj.toString = function() { return klassName };
- console.log(obj);
- ;})
- ]]></>.toString(),
- ObjectInspecter.serialize(arg),
- getQualifiedClassName(arg)
- );
+ try {
+ ExternalInterface.call(<><![CDATA[
+ (function(obj, klassName) {
+ obj.toString = function() { return klassName };
+ console.log(obj);
+ ;})
+ ]]></>.toString(),
+ ObjectInspecter.serialize(arg),
+ getQualifiedClassName(arg)
+ );
+ } catch(e:Error) {
+ ExternalInterface.call('console.log', r);
+ }
}
return r;
}
}
|
hotchpotch/as3rails2u
|
c81cc0df2afccc0fcdfacb9aef50201d8ac464b6
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@46 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/utils/ObjectInspecter.as b/src/com/rails2u/utils/ObjectInspecter.as
index d38ec31..0901f84 100644
--- a/src/com/rails2u/utils/ObjectInspecter.as
+++ b/src/com/rails2u/utils/ObjectInspecter.as
@@ -1,65 +1,65 @@
package com.rails2u.utils
{
import flash.utils.getQualifiedClassName;
import flash.utils.ByteArray;
public class ObjectInspecter
{
/*
*
*/
public static function inspect(... args):String {
return inspectImpl(args, false);
}
- public static function seriarize(arg:Object):Object {
+ public static function serialize(arg:Object):Object {
var b:ByteArray = new ByteArray();
b.writeObject(arg);
b.position = 0;
return b.readObject();
}
internal static function inspectImpl(arg:*, bracket:Boolean = true):String {
var className:String = getQualifiedClassName(arg);
var str:String; var results:Array;
switch(getQualifiedClassName(arg)) {
case 'Object':
case 'Dictionary':
results = [];
for (var key:* in arg) {
results.push(inspectImpl(key) + ':' + inspectImpl(arg[key], false));
}
str = classFormat(className, '{' + results.join(', ') + '}');
// str = classFormat(className, arg);
break;
case 'Array':
results = [];
for (var i:uint = 0; i < arg.length; i++) {
results.push(inspectImpl(arg[i]));
}
if (bracket) {
str = '[' + results.join(', ') + ']';
} else {
str = results.join(', ');
}
break;
case 'int':
case 'uint':
case 'Number':
str = arg.toString();
break;
case 'String':
str = arg;
break;
default:
str = classFormat(className, arg);
}
return str;
}
internal static function classFormat(className:String, arg:*):String {
return '#<' + className + ':' + String(arg) + '>';
}
}
}
diff --git a/src/log.as b/src/log.as
index fd3e5e7..8890d28 100644
--- a/src/log.as
+++ b/src/log.as
@@ -1,37 +1,37 @@
package {
import flash.external.ExternalInterface;
import com.rails2u.utils.ObjectInspecter;
import flash.utils.getQualifiedClassName;
/**
* log() is Object inspect dump output to trace() and use
* Browser(FireFox, Safari and more) External API console.log.
*
* example
* <listing version="3.0">
* var a:Array = [[1,2,3], [4,[5,6]]];
* var sprite:Sprite = new Sprite;
* log(a, sprite);
* # output
* [[1, 2, 3], [4, [5, 6]]], #<flash.display::Sprite:[object Sprite]>
* </listing>
*/
public function log(... args):String {
var r:String = ObjectInspecter.inspect.apply(null, args);
trace(r)
if (ExternalInterface.available) {
var arg:* = args.length == 1 ? args[0] : args;
ExternalInterface.call(<><![CDATA[
(function(obj, klassName) {
obj.toString = function() { return klassName };
console.log(obj);
;})
]]></>.toString(),
- ObjectInspecter.seriarize(arg),
+ ObjectInspecter.serialize(arg),
getQualifiedClassName(arg)
);
}
return r;
}
}
|
hotchpotch/as3rails2u
|
d6bc33dd713b04ccf100aaa3327cd3568fa323fa
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@45 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/utils/ObjectInspecter.as b/src/com/rails2u/utils/ObjectInspecter.as
index b7745d5..d38ec31 100644
--- a/src/com/rails2u/utils/ObjectInspecter.as
+++ b/src/com/rails2u/utils/ObjectInspecter.as
@@ -1,57 +1,65 @@
package com.rails2u.utils
{
import flash.utils.getQualifiedClassName;
+ import flash.utils.ByteArray;
public class ObjectInspecter
{
/*
*
*/
public static function inspect(... args):String {
return inspectImpl(args, false);
}
+ public static function seriarize(arg:Object):Object {
+ var b:ByteArray = new ByteArray();
+ b.writeObject(arg);
+ b.position = 0;
+ return b.readObject();
+ }
+
internal static function inspectImpl(arg:*, bracket:Boolean = true):String {
var className:String = getQualifiedClassName(arg);
var str:String; var results:Array;
switch(getQualifiedClassName(arg)) {
case 'Object':
case 'Dictionary':
results = [];
for (var key:* in arg) {
results.push(inspectImpl(key) + ':' + inspectImpl(arg[key], false));
}
str = classFormat(className, '{' + results.join(', ') + '}');
// str = classFormat(className, arg);
break;
case 'Array':
results = [];
for (var i:uint = 0; i < arg.length; i++) {
results.push(inspectImpl(arg[i]));
}
if (bracket) {
str = '[' + results.join(', ') + ']';
} else {
str = results.join(', ');
}
break;
case 'int':
case 'uint':
case 'Number':
str = arg.toString();
break;
case 'String':
str = arg;
break;
default:
str = classFormat(className, arg);
}
return str;
}
internal static function classFormat(className:String, arg:*):String {
return '#<' + className + ':' + String(arg) + '>';
}
}
}
diff --git a/src/log.as b/src/log.as
index b57bae0..fd3e5e7 100644
--- a/src/log.as
+++ b/src/log.as
@@ -1,24 +1,37 @@
package {
import flash.external.ExternalInterface;
import com.rails2u.utils.ObjectInspecter;
+ import flash.utils.getQualifiedClassName;
/**
- * log() is Object inspect dump output to trace() and use
- * Browser(FireFox, Safari and more) External API console.log.
- *
- * example
- * <listing version="3.0">
- * var a:Array = [[1,2,3], [4,[5,6]]];
- * var sprite:Sprite = new Sprite;
- * log(a, sprite);
- * # output
- * [[1, 2, 3], [4, [5, 6]]], #<flash.display::Sprite:[object Sprite]>
- * </listing>
- */
+ * log() is Object inspect dump output to trace() and use
+ * Browser(FireFox, Safari and more) External API console.log.
+ *
+ * example
+ * <listing version="3.0">
+ * var a:Array = [[1,2,3], [4,[5,6]]];
+ * var sprite:Sprite = new Sprite;
+ * log(a, sprite);
+ * # output
+ * [[1, 2, 3], [4, [5, 6]]], #<flash.display::Sprite:[object Sprite]>
+ * </listing>
+ */
public function log(... args):String {
var r:String = ObjectInspecter.inspect.apply(null, args);
trace(r)
- ExternalInterface.call('console.log', r);
+ if (ExternalInterface.available) {
+ var arg:* = args.length == 1 ? args[0] : args;
+
+ ExternalInterface.call(<><![CDATA[
+ (function(obj, klassName) {
+ obj.toString = function() { return klassName };
+ console.log(obj);
+ ;})
+ ]]></>.toString(),
+ ObjectInspecter.seriarize(arg),
+ getQualifiedClassName(arg)
+ );
+ }
return r;
}
}
|
hotchpotch/as3rails2u
|
44516e951f3cb17388e32f43beaf65b85c8f5cfc
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@44 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/debug/DebugWatcher.as b/src/com/rails2u/debug/DebugWatcher.as
index cb1754c..70da031 100644
--- a/src/com/rails2u/debug/DebugWatcher.as
+++ b/src/com/rails2u/debug/DebugWatcher.as
@@ -1,39 +1,39 @@
package com.rails2u.debug {
import flash.events.IEventDispatcher;
import com.rails2u.utils.Reflection;
import flash.events.Event;
- import mx.logging.Log;
+
public class DebugWatcher {
public static function monitorEvents(target:IEventDispatcher, ... arg):void {
if ( arg.length > 0 ) {
for each(var evName:String in arg) {
target.addEventListener(evName, eventLog);
}
} else {
var targetRefrection:Reflection = Reflection.factory(target);
var eventlist:Array = targetRefrection.getAllDispatchEvents();
for each(var ary:Object in eventlist) {
if(ary.name != Event.ENTER_FRAME) target.addEventListener(ary.name, eventLog);
}
}
}
public static function unmonitorEvents(target:IEventDispatcher, ... arg):void {
if ( arg.length > 0 ) {
for each(var evName:String in arg) {
target.removeEventListener(evName, eventLog);
}
} else {
var targetRefrection:Reflection = Reflection.factory(target);
var eventlist:Array = targetRefrection.getAllDispatchEvents();
for each(var ary:Object in eventlist) {
if(ary.name != Event.ENTER_FRAME) target.removeEventListener(ary.name, eventLog);
}
}
}
protected static function eventLog(e:Event):void {
log(e);
}
}
}
diff --git a/src/com/rails2u/net/JSONPLoader.as b/src/com/rails2u/net/JSONPLoader.as
index cf8e003..c5eb08d 100644
--- a/src/com/rails2u/net/JSONPLoader.as
+++ b/src/com/rails2u/net/JSONPLoader.as
@@ -1,133 +1,134 @@
package com.rails2u.net {
import flash.events.EventDispatcher;
import flash.external.ExternalInterface;
import flash.events.Event;
import flash.errors.IllegalOperationError;
import flash.events.TimerEvent;
import flash.events.IOErrorEvent;
import flash.utils.Timer;
import flash.system.Security;
/**
* How to use:
* // JSONPLoader.allowCurrentDomain(); // Allow show browsing url's domain.
* var loader:JSONPLoader = new JSONPLoader();
* loader.addEventListener(Event.COMPLETE, function(e:Event):void {
* log(e.target.data);
* });
* loader.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void {
* log('error!');
* });
* // loader.callbackQueryName = 'callback'; // Default name is "callback"
* loader.load('http://del.icio.us/feeds/json/url/data?hash=46efc577b7ddef30d1c6fd13311b371e');
*/
+
public class JSONPLoader extends EventDispatcher {
public var encoding:String = 'UTF-8';
public var callbackQueryName:String = 'callback';
public var data:Object;
public var timeout:Number = 30;
protected var nowCallbackFuncName:String;
public static var callbackObjects:Object = {};
public static var inited:Boolean = false;
public function JSONPLoader(url:String = undefined):void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
if (!inited) init();
if (url) load(url);
}
public static function allowCurrentDomain():void {
var domain:String = execExternalInterface('return location.host.split(":", 2)[0]');
Security.allowDomain(domain);
}
protected static function init():void {
inited = true;
ExternalInterface.addCallback('jsonpCallbacks', jsonpCallbacks);
}
public function load(url:String):void {
if (observeTimer) {
jsRemoveCallback(nowCallbackFuncName);
clearObserveTimer();
}
var callbackFuncName:String = '_' + (new Date()).getTime().toString();
nowCallbackFuncName = callbackFuncName;
jsAddCallback(callbackFuncName);
var loadURL:String = url + ((url.indexOf('?') > 0) ? '&' : '?') +
encodeURIComponent(callbackQueryName) + '=' + encodeURIComponent('as3callbacks.' + callbackFuncName);
callbackObjects[callbackFuncName] = this;
observeTimeout(timeout, callbackFuncName);
createScriptElement(loadURL);
}
protected function createScriptElement(loadURL:String):void {
var js:Array = [];
js.push("var script = document.createElement('script');");
js.push("script.charset = '" + encoding + "';");
js.push("script.src = '" + loadURL + "';");
js.push("setTimeout(function(){document.body.appendChild(script);}, 10);");
dispatchEvent(new Event(Event.OPEN));
execExternalInterface(js.join("\n"));
}
protected static function jsonpCallbacks(callbackFuncName:String, obj:Object):void {
var target:JSONPLoader = callbackObjects[callbackFuncName] as JSONPLoader;
if (target) {
target.data = obj;
target.dispatchEvent(new Event(Event.COMPLETE));
target.clearObserveTimer();
} else {
new Error("Don't found callback(" + callbackFuncName + ").");
}
}
protected static function execExternalInterface(cmd:String):* {
cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
protected function jsAddCallback(callbackFuncName:String):void {
var js:String = 'if (!window.as3callbacks) window.as3callbacks = {};window.as3callbacks["' + callbackFuncName +
'"] = function(obj) { document.getElementsByName("' +
ExternalInterface.objectID + '")[0].jsonpCallbacks("' + callbackFuncName + '",obj) };';
execExternalInterface(js);
}
protected function jsRemoveCallback(callbackFuncName:String):void {
var js:String = 'if (window.as3callbacks) window.as3callbacks["' + callbackFuncName + '"] = function() {};';
execExternalInterface(js);
}
protected var observeTimer:Timer;
protected function observeTimeout(sec:Number, callbackFuncName:String):void
{
observeTimer = new Timer(sec * 1000, 1);
observeTimer.addEventListener(TimerEvent.TIMER, timeoutErrorHandlerBind(callbackFuncName), false, 1, true);
observeTimer.start();
}
protected function timeoutErrorHandlerBind(callbackFuncName:String):Function {
return function(e:TimerEvent):void {
jsRemoveCallback(callbackFuncName);
timeoutErrorHandler(e);
}
}
protected function timeoutErrorHandler(e:TimerEvent):void
{
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, 'Request timeout'));
clearObserveTimer();
}
// FIXME: Public namespace should be protected.
public function clearObserveTimer():void {
observeTimer.removeEventListener(TimerEvent.TIMER, timeoutErrorHandler);
observeTimer.stop();
observeTimer = null;
}
}
}
diff --git a/src/com/rails2u/swflayer/SWFLayer.as b/src/com/rails2u/swflayer/SWFLayer.as
index 87cb065..647e92b 100644
--- a/src/com/rails2u/swflayer/SWFLayer.as
+++ b/src/com/rails2u/swflayer/SWFLayer.as
@@ -1,165 +1,165 @@
package com.rails2u.swflayer {
import flash.external.ExternalInterface;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.errors.IOError;
import flash.errors.IllegalOperationError;
public dynamic class SWFLayer extends Proxy {
private static var _instance:SWFLayer;
private static var _style:SWFStyle;
public function SWFLayer() {
if (SWFLayer._instance) throw (new ArgumentError('Please access SWFLayer.getInstance()'));
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
// defineJSFuncitons();
- var x:String = getProperty('offsetTop');
- var y:String = getProperty('offsetLeft');
+ //var x:String = getProperty('offsetTop');
+ //var y:String = getProperty('offsetLeft');
_style = new SWFStyle(this);
//this.x = Number(x);
//this.y = Number(y);
//this.height = this.clientHeight;
//this.width = this.clientWidth;
- if (_style.position != 'absolute') _style.position = 'absolute';
+ //if (_style.position != 'absolute') _style.position = 'absolute';
}
public function get style():SWFStyle {
return _style;
}
public static function getInstance():SWFLayer {
return _instance ||= new SWFLayer();
}
public static function get instance():SWFLayer {
return _instance ||= new SWFLayer();
}
public function set width(value:Number):void {
if (isNaN(value)) {
_style.setStyle('width', SWFStyle.AUTO);
} else {
_style.setStyle('width', value.toString());
}
}
public function get width():Number {
return Number(_style.getStyle('width'));
}
public function set height(value:Number):void {
if (isNaN(value)) {
_style.setStyle('height', SWFStyle.AUTO);
} else {
_style.setStyle('height', value.toString());
}
}
public function get height():Number {
return Number(style.getStyle('height'));
}
public function set x(value:Number):void {
_style.setStyle('left', value.toString());
}
public function get x():Number {
try {
return Number(_style.getStyle('left').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
public function set y(value:Number):void {
_style.setStyle('top', value.toString());
}
public function get y():Number {
try {
return Number(_style.getStyle('top').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
public function fitInBrowser():void {
this.x = this.scrollLeft;
this.y = this.scrollTop;
this.width = this.browserWidth;
this.height = this.browserHeight;
}
public function get browserWidth():Number {
//return execExternalInterface('return document.body.clientWidth') as Number; // IOError ;(
return execExternalInterface('return document.getElementsByTagName("body")[0].clientWidth') as Number;
}
public function get browserHeight():Number {
return execExternalInterface('return document.getElementsByTagName("body")[0].clientHeight') as Number;
}
public function get htmlWidth():Number {
return execExternalInterface('return document.getElementsByTagName("html")[0].clientWidth') as Number;
}
public function get htmlHeight():Number {
return execExternalInterface('return document.getElementsByTagName("html")[0].clientHeight') as Number;
}
public function get scrollTop():Number {
return execExternalInterface('return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop') as Number;
}
public function get scrollLeft():Number {
return execExternalInterface('return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft') as Number;
}
public function get objectID():String {
return ExternalInterface.objectID;
}
public function setProperty(name:String, value:String):void {
exec(name + ' = "' + value + '"');
}
public function getProperty(name:String):* {
return exec(name);
}
public function exec(cmd:String):* {
cmd = "return document.getElementById('" + objectID + "')." + cmd;
return execExternalInterface(cmd);
}
public static function execExternalInterface(cmd:String):* {
cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
override flash_proxy function setProperty(name:*, value:*):void {
this.setProperty(name, value);
}
override flash_proxy function getProperty(name:*):* {
return this.getProperty(name);
}
override flash_proxy function callProperty(name:*, ...rest):* {
}
private function getterClosure(name:String):Function {
var self:SWFLayer = this;
return function():* { return self[name] };
}
private function defineJSFuncitons():void {
ExternalInterface.addCallback('fitInBrowser', fitInBrowser);
var a:Array = ['browserWidth', 'browserHeight', 'htmlWidth', 'htmlHeight', 'scrollTop', 'scrollLeft', 'x', 'y', 'width', 'height'];
for each (var closureName:String in a) {
ExternalInterface.addCallback(closureName, getterClosure(closureName));
}
}
}
}
diff --git a/src/com/rails2u/utils/MathUtil.as b/src/com/rails2u/utils/MathUtil.as
index 040cf39..5e0b321 100644
--- a/src/com/rails2u/utils/MathUtil.as
+++ b/src/com/rails2u/utils/MathUtil.as
@@ -1,66 +1,90 @@
package com.rails2u.utils
{
public class MathUtil
{
public static function randomPlusMinus(val:Number = 1):Number {
if (randomBoolean() ) {
return val;
} else {
return val * -1;
}
}
/*
* randomBoolean(-100, 100); // retun value is between -100 and 100;
*/
public static function randomBetween(s:Number, e:Number = 0):Number {
return s + (e - s) * Math.random();
}
/*
* randomBetween(); // return value is true or false.
*/
public static function randomBoolean():Boolean {
return (Math.round(Math.random()) == 1) ? true : false;
}
/*
* randomPickup(1,2,3,4); // return value is 1 or 2 or 3 or 4
*/
public static function randomPickup(... args):Object {
var len:uint = args.length;
if (len == 1) {
return args[0];
} else {
return args[Math.round(Math.random() * (len - 1))];
}
}
/*
* var cycleABC = MathUtil.cycle('a', 'b', 'c');
* cycleABC(); // 'a'
* cycleABC(); // 'b'
* cycleABC(); // 'c'
* cycleABC(); // 'a'
* cycleABC(); // 'b'
*/
public static function cycle(... args):Function {
var len:uint = args.length;
var i:uint = 0;
if (len == 1) {
return function():Object {
return args[0];
}
} else {
return function():Object {
var res:Object = args[i];
i++;
if (i >= len) i = 0;
return res;
};
}
}
+ public static function bezier3(t:Number, x0:Number, x1:Number, x2:Number, x3:Number):Number {
+ return x0 * Math.pow(1-t, 3) + 3 * x1 * t *Math.pow(1-t, 2) + 3 * x2 * Math.pow(t, 2) * 1-t + x3 * Math.pow(t, 3);
+ }
+
+ public static function bezierN(t:Number, points:Array):Number {
+ var res:Number = 0;
+ var len:uint = points.length;
+ var tm:Number = 1 - t;
+ for (var i:uint=0; i < len;i++) {
+ var pos:Number = points[i];
+ var tmp:Number = 1.0;
+ var a:Number = len - 1;
+ var b:Number = i;
+ var c:Number = a - b;
+ while (a > 1) {
+ if(a > 1) tmp *= a; a -= 1;
+ if(b > 1) tmp /= b; b -= 1;
+ if(c > 1) tmp /= c; c -= 1;
+ }
+ tmp *= Math.pow(t, i) * Math.pow(tm, len -1 -i);
+ res += tmp * pos;
+ }
+ return res;
+ }
}
}
|
hotchpotch/as3rails2u
|
36665dfe40b184c7e4302972364494b8dbb54ed3
|
remove loop method
|
diff --git a/src/com/rails2u/debug/Benchmark.as b/src/com/rails2u/debug/Benchmark.as
index eea3608..abecbdc 100644
--- a/src/com/rails2u/debug/Benchmark.as
+++ b/src/com/rails2u/debug/Benchmark.as
@@ -1,48 +1,42 @@
package com.rails2u.debug {
import flash.utils.Dictionary;
import flash.events.Event;
import flash.utils.getTimer;
/**
* Simple Benchmark class
*
* example:
* <listing version="3.0">
* Benchmark.start('check');
* // code
* Benchmark.end('check');
* </listing>
*
* <listing version="3.0">
* Benchmark.benchmark('check2', function() {
* // code
* }, this);
* </listing>
*/
public class Benchmark {
private static var dict:Object = {};
public static function start(name:String):void {
dict[name] = getTimer();
}
- public static function benchmark(name:String, callback:Function, bindObject:Object = null):Number {
- start(name);
- callback.call(bindObject);
- return end(name);
- }
-
- public static function loop(name:String, callback:Function, bindObject:Object = null, times:uint = 100):Number {
+ public static function benchmark(name:String, callback:Function, bindObject:Object = null, times:uint = 1):Number {
start(name);
for (var i:uint = 0; i < times; i++)
callback.call(bindObject);
return end(name);
}
public static function end(name:String):Number {
var re:uint = getTimer() - dict[name];
log(name + ':' + ' ' + re + 'ms');
return re;
}
}
}
|
hotchpotch/as3rails2u
|
db0bfd74eadaa2e188d075459acaca6404bb716d
|
add loop method
|
diff --git a/src/com/rails2u/debug/Benchmark.as b/src/com/rails2u/debug/Benchmark.as
index e8f7905..eea3608 100644
--- a/src/com/rails2u/debug/Benchmark.as
+++ b/src/com/rails2u/debug/Benchmark.as
@@ -1,41 +1,48 @@
package com.rails2u.debug {
import flash.utils.Dictionary;
import flash.events.Event;
import flash.utils.getTimer;
/**
* Simple Benchmark class
*
* example:
* <listing version="3.0">
* Benchmark.start('check');
* // code
* Benchmark.end('check');
* </listing>
*
* <listing version="3.0">
* Benchmark.benchmark('check2', function() {
* // code
* }, this);
* </listing>
*/
public class Benchmark {
private static var dict:Object = {};
public static function start(name:String):void {
dict[name] = getTimer();
}
public static function benchmark(name:String, callback:Function, bindObject:Object = null):Number {
start(name);
- callback.apply(bindObject);
+ callback.call(bindObject);
+ return end(name);
+ }
+
+ public static function loop(name:String, callback:Function, bindObject:Object = null, times:uint = 100):Number {
+ start(name);
+ for (var i:uint = 0; i < times; i++)
+ callback.call(bindObject);
return end(name);
}
public static function end(name:String):Number {
var re:uint = getTimer() - dict[name];
log(name + ':' + ' ' + re + 'ms');
return re;
}
}
}
|
hotchpotch/as3rails2u
|
ed687403f0cd5ce22ec775e64dbbc95111f7a4f5
|
fix mail addr.....
|
diff --git a/licence.txt b/licence.txt
index 8417a36..440f7bb 100644
--- a/licence.txt
+++ b/licence.txt
@@ -1,24 +1,24 @@
-Yuichi Tateno. <hotch_potch@[email protected]>
+Yuichi Tateno. <hotchpotch@[email protected]>
http://rails2u.com/
THE MIT License
--------
Copyright (c) 2007 Yuichi Tateno.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
|
hotchpotch/as3rails2u
|
010088670875de8432774d0fdb53c906cacdd7a3
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@39 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/net/JSONPLoader.as b/src/com/rails2u/net/JSONPLoader.as
index b34217f..751a465 100644
--- a/src/com/rails2u/net/JSONPLoader.as
+++ b/src/com/rails2u/net/JSONPLoader.as
@@ -1,71 +1,104 @@
package com.rails2u.net {
import flash.events.EventDispatcher;
import flash.external.ExternalInterface;
import flash.events.Event;
import flash.errors.IllegalOperationError;
+ import flash.events.TimerEvent;
+ import flash.events.IOErrorEvent;
+ import flash.utils.Timer;
public class JSONPLoader extends EventDispatcher {
public static var callbackObjects:Object = {};
public var url:String;
public var encoding:String = 'UTF-8';
public var callbackQueryName:String = 'callback';
public var data:Object;
+ public var timeout:Number = 30;
public static var inited:Boolean = false;
public function JSONPLoader(url:String = ''):void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
-
if (!inited) init();
+
this.url = url;
}
private function init():void {
inited = true;
ExternalInterface.addCallback('jsonpCallbacks', jsonpCallbacks);
}
- private function jsFuncRegister(callbackFuncName:String):void {
- var js:String = 'if (!window.as3callbacks) window.as3callbacks = {};window.as3callbacks["' + callbackFuncName +
- '"] = function(obj) { document.getElementById("' +
- ExternalInterface.objectID + '").jsonpCallbacks("' + callbackFuncName + '",obj) };';
- log(js);
- execExternalInterface(js);
- }
-
- public function load():void {
+ public function load(url:String = undefined):void {
+ url ||= this.url;
var callbackFuncName:String = '_' + (new Date()).getTime().toString();
- log(callbackFuncName);
- jsFuncRegister(callbackFuncName);
+ jsAddCallback(callbackFuncName);
var loadURL:String = url + ((url.indexOf('?') > 0) ? '&' : '?') +
encodeURIComponent(callbackQueryName) + '=' + encodeURIComponent('as3callbacks.' + callbackFuncName);
callbackObjects[callbackFuncName] = this;
+ observeTimeout(timeout, callbackFuncName);
createScriptElement(loadURL);
}
private function createScriptElement(loadURL:String):void {
var js:Array = [];
js.push("var script = document.createElement('script');");
js.push("script.charset = '" + encoding + "';");
js.push("script.src = '" + loadURL + "';");
js.push("setTimeout(function(){document.body.appendChild(script);}, 10);");
+ dispatchEvent(new Event(Event.OPEN));
execExternalInterface(js.join("\n"));
}
private static function jsonpCallbacks(callbackFuncName:String, obj:Object):void {
var target:JSONPLoader = callbackObjects[callbackFuncName] as JSONPLoader;
if (target) {
target.data = obj;
target.dispatchEvent(new Event(Event.COMPLETE));
}
}
private static function execExternalInterface(cmd:String):* {
cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
+
+ private function jsAddCallback(callbackFuncName:String):void {
+ var js:String = 'if (!window.as3callbacks) window.as3callbacks = {};window.as3callbacks["' + callbackFuncName +
+ '"] = function(obj) { document.getElementById("' +
+ ExternalInterface.objectID + '").jsonpCallbacks("' + callbackFuncName + '",obj) };';
+ execExternalInterface(js);
+ }
+
+ private function jsRemoveCallback(callbackFuncName:String):void {
+ var js:String = 'if (window.as3callbacks) window.as3callbacks["' + callbackFuncName + '"] = function() {};';
+ execExternalInterface(js);
+ }
+
+ private var observeTimer:Timer;
+ private function observeTimeout(sec:Number, callbackFuncName:String):void
+ {
+ observeTimer = new Timer(sec * 1000, 1);
+ observeTimer.addEventListener(TimerEvent.TIMER, timeoutErrorHandlerBind(callbackFuncName), false, 1, true);
+ observeTimer.start();
+ }
+
+ private function timeoutErrorHandlerBind(callbackFuncName:String):Function {
+ return function(e:TimerEvent):void {
+ jsRemoveCallback(callbackFuncName);
+ timeoutErrorHandler(e);
+ }
+ }
+
+ private function timeoutErrorHandler(e:TimerEvent):void
+ {
+ dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, 'Request timeout'));
+ observeTimer.removeEventListener(TimerEvent.TIMER, timeoutErrorHandler);
+ observeTimer.stop();
+ observeTimer = null;
+ }
}
}
diff --git a/src/com/rails2u/net/URLLoaderWithTimeout.as b/src/com/rails2u/net/URLLoaderWithTimeout.as
index 5f9b880..9341cd0 100644
--- a/src/com/rails2u/net/URLLoaderWithTimeout.as
+++ b/src/com/rails2u/net/URLLoaderWithTimeout.as
@@ -1,52 +1,53 @@
package com.rails2u.net
{
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.events.Event;
import flash.events.IOErrorEvent;
/*
* URLLoader with Timeout
* loader.addEventListener(IOErrorEvent.IO_ERROR,
* function(e:*):void { trace('timeout!') });
- * loader.loadWithTimeout(request, 30);
*/
+ * loader.loadWithTimeout(request, 30);
+ */
public class URLLoaderWithTimeout extends URLLoader
{
public function URLLoaderWithTimeout(request:URLRequest=null)
{
super(request);
}
public function loadWithTimeout(request:URLRequest, timeout:Number = 30):void
{
addEventListener(Event.COMPLETE, cancelTimeoutError, false, 1, true);
observeTimeout(timeout);
load(request);
}
private var observeTimer:Timer;
private function observeTimeout(sec:Number):void
{
observeTimer = new Timer(sec * 1000, 1);
observeTimer.addEventListener(
TimerEvent.TIMER, timeoutError, false, 1, true
);
observeTimer.start();
}
private function cancelTimeoutError(e:Event):void
{
if (observeTimer) {
observeTimer.removeEventListener(TimerEvent.TIMER, timeoutError);
}
}
private function timeoutError(e:TimerEvent):void
{
dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, false, false, 'request timeout'));
observeTimer = null;
}
}
-}
\ No newline at end of file
+}
|
hotchpotch/as3rails2u
|
e61e90bc2527b8143f8262318e220b44b5f270c9
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@38 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/net/JSONPLoader.as b/src/com/rails2u/net/JSONPLoader.as
new file mode 100644
index 0000000..b34217f
--- /dev/null
+++ b/src/com/rails2u/net/JSONPLoader.as
@@ -0,0 +1,71 @@
+package com.rails2u.net {
+ import flash.events.EventDispatcher;
+ import flash.external.ExternalInterface;
+ import flash.events.Event;
+ import flash.errors.IllegalOperationError;
+
+ public class JSONPLoader extends EventDispatcher {
+ public static var callbackObjects:Object = {};
+
+ public var url:String;
+ public var encoding:String = 'UTF-8';
+ public var callbackQueryName:String = 'callback';
+ public var data:Object;
+
+ public static var inited:Boolean = false;
+
+ public function JSONPLoader(url:String = ''):void {
+ if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
+
+ if (!inited) init();
+ this.url = url;
+ }
+
+ private function init():void {
+ inited = true;
+ ExternalInterface.addCallback('jsonpCallbacks', jsonpCallbacks);
+
+ }
+
+ private function jsFuncRegister(callbackFuncName:String):void {
+ var js:String = 'if (!window.as3callbacks) window.as3callbacks = {};window.as3callbacks["' + callbackFuncName +
+ '"] = function(obj) { document.getElementById("' +
+ ExternalInterface.objectID + '").jsonpCallbacks("' + callbackFuncName + '",obj) };';
+ log(js);
+ execExternalInterface(js);
+ }
+
+ public function load():void {
+ var callbackFuncName:String = '_' + (new Date()).getTime().toString();
+ log(callbackFuncName);
+ jsFuncRegister(callbackFuncName);
+
+ var loadURL:String = url + ((url.indexOf('?') > 0) ? '&' : '?') +
+ encodeURIComponent(callbackQueryName) + '=' + encodeURIComponent('as3callbacks.' + callbackFuncName);
+ callbackObjects[callbackFuncName] = this;
+ createScriptElement(loadURL);
+ }
+
+ private function createScriptElement(loadURL:String):void {
+ var js:Array = [];
+ js.push("var script = document.createElement('script');");
+ js.push("script.charset = '" + encoding + "';");
+ js.push("script.src = '" + loadURL + "';");
+ js.push("setTimeout(function(){document.body.appendChild(script);}, 10);");
+ execExternalInterface(js.join("\n"));
+ }
+
+ private static function jsonpCallbacks(callbackFuncName:String, obj:Object):void {
+ var target:JSONPLoader = callbackObjects[callbackFuncName] as JSONPLoader;
+ if (target) {
+ target.data = obj;
+ target.dispatchEvent(new Event(Event.COMPLETE));
+ }
+ }
+
+ private static function execExternalInterface(cmd:String):* {
+ cmd = "(function() {" + cmd + ";})";
+ return ExternalInterface.call(cmd);
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
8aaa8335230862944b76a70c068da97b854d3a70
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@37 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/swflayer/SWFLayer.as b/src/com/rails2u/swflayer/SWFLayer.as
index 46a8132..87cb065 100644
--- a/src/com/rails2u/swflayer/SWFLayer.as
+++ b/src/com/rails2u/swflayer/SWFLayer.as
@@ -1,146 +1,165 @@
package com.rails2u.swflayer {
import flash.external.ExternalInterface;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.errors.IOError;
+ import flash.errors.IllegalOperationError;
public dynamic class SWFLayer extends Proxy {
private static var _instance:SWFLayer;
private static var _style:SWFStyle;
+
public function SWFLayer() {
- if(SWFLayer._instance) throw(new ArgumentError('Please access SWFLayer.getInstance()'));
+ if (SWFLayer._instance) throw (new ArgumentError('Please access SWFLayer.getInstance()'));
+ if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
+
+ // defineJSFuncitons();
var x:String = getProperty('offsetTop');
var y:String = getProperty('offsetLeft');
_style = new SWFStyle(this);
- this.x = Number(x);
- this.y = Number(y);
- this.height = this.clientHeight;
- this.width = this.clientWidth;
+ //this.x = Number(x);
+ //this.y = Number(y);
+ //this.height = this.clientHeight;
+ //this.width = this.clientWidth;
if (_style.position != 'absolute') _style.position = 'absolute';
}
public function get style():SWFStyle {
return _style;
}
public static function getInstance():SWFLayer {
return _instance ||= new SWFLayer();
}
public static function get instance():SWFLayer {
return _instance ||= new SWFLayer();
}
public function set width(value:Number):void {
if (isNaN(value)) {
_style.setStyle('width', SWFStyle.AUTO);
} else {
_style.setStyle('width', value.toString());
}
}
public function get width():Number {
return Number(_style.getStyle('width'));
}
public function set height(value:Number):void {
if (isNaN(value)) {
_style.setStyle('height', SWFStyle.AUTO);
} else {
_style.setStyle('height', value.toString());
}
}
public function get height():Number {
return Number(style.getStyle('height'));
}
public function set x(value:Number):void {
_style.setStyle('left', value.toString());
}
public function get x():Number {
try {
return Number(_style.getStyle('left').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
public function set y(value:Number):void {
_style.setStyle('top', value.toString());
}
public function get y():Number {
try {
return Number(_style.getStyle('top').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
public function fitInBrowser():void {
- this.x = this.scrollLeft;
- this.y = this.scrollTop;
- this.width = this.browserWidth;
- this.height = this.browserHeight;
+ this.x = this.scrollLeft;
+ this.y = this.scrollTop;
+ this.width = this.browserWidth;
+ this.height = this.browserHeight;
}
public function get browserWidth():Number {
- //return execExternalIntarface('return document.body.clientWidth') as Number; // IOError ;(
- return execExternalIntarface('return document.getElementsByTagName("body")[0].clientWidth') as Number;
+ //return execExternalInterface('return document.body.clientWidth') as Number; // IOError ;(
+ return execExternalInterface('return document.getElementsByTagName("body")[0].clientWidth') as Number;
}
public function get browserHeight():Number {
- return execExternalIntarface('return document.getElementsByTagName("body")[0].clientHeight') as Number;
+ return execExternalInterface('return document.getElementsByTagName("body")[0].clientHeight') as Number;
}
public function get htmlWidth():Number {
- return execExternalIntarface('return document.getElementsByTagName("html")[0].clientWidth') as Number;
+ return execExternalInterface('return document.getElementsByTagName("html")[0].clientWidth') as Number;
}
public function get htmlHeight():Number {
- return execExternalIntarface('return document.getElementsByTagName("html")[0].clientHeight') as Number;
+ return execExternalInterface('return document.getElementsByTagName("html")[0].clientHeight') as Number;
}
public function get scrollTop():Number {
- return execExternalIntarface('return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop') as Number;
+ return execExternalInterface('return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop') as Number;
}
public function get scrollLeft():Number {
- return execExternalIntarface('return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft') as Number;
+ return execExternalInterface('return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft') as Number;
}
public function get objectID():String {
return ExternalInterface.objectID;
}
public function setProperty(name:String, value:String):void {
exec(name + ' = "' + value + '"');
}
public function getProperty(name:String):* {
return exec(name);
}
public function exec(cmd:String):* {
cmd = "return document.getElementById('" + objectID + "')." + cmd;
- return execExternalIntarface(cmd);
+ return execExternalInterface(cmd);
}
- public static function execExternalIntarface(cmd:String):* {
+ public static function execExternalInterface(cmd:String):* {
cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
override flash_proxy function setProperty(name:*, value:*):void {
this.setProperty(name, value);
}
override flash_proxy function getProperty(name:*):* {
return this.getProperty(name);
}
override flash_proxy function callProperty(name:*, ...rest):* {
}
+
+ private function getterClosure(name:String):Function {
+ var self:SWFLayer = this;
+ return function():* { return self[name] };
+ }
+
+ private function defineJSFuncitons():void {
+ ExternalInterface.addCallback('fitInBrowser', fitInBrowser);
+
+ var a:Array = ['browserWidth', 'browserHeight', 'htmlWidth', 'htmlHeight', 'scrollTop', 'scrollLeft', 'x', 'y', 'width', 'height'];
+ for each (var closureName:String in a) {
+ ExternalInterface.addCallback(closureName, getterClosure(closureName));
+ }
+ }
}
}
diff --git a/src/com/rails2u/utils/ColorUtil.as b/src/com/rails2u/utils/ColorUtil.as
index 91ac765..a651729 100644
--- a/src/com/rails2u/utils/ColorUtil.as
+++ b/src/com/rails2u/utils/ColorUtil.as
@@ -1,56 +1,57 @@
package com.rails2u.utils
{
public class ColorUtil
{
public static function random(
rMin:uint = 0,
gMin:uint = 0,
bMin:uint = 0,
rMax:uint = 255,
gMax:uint = 255,
bMax:uint = 255
):uint
{
return (uint(Math.random() * (rMax - rMin)) + rMin) << 16 |
(uint(Math.random() * (gMax - gMin)) + gMin) << 8 |
(uint(Math.random() * (bMax - bMin)) + bMin);
}
public static function random32(
rMin:uint = 0,
gMin:uint = 0,
bMin:uint = 0,
aMin:uint = 0,
rMax:uint = 255,
gMax:uint = 255,
bMax:uint = 255,
aMax:uint = 255
):uint
{
return (uint(Math.random() * (aMax - aMin)) + aMin) << 24 |
(uint(Math.random() * (rMax - rMin)) + rMin) << 16 |
(uint(Math.random() * (gMax - gMin)) + gMin) << 8 |
(uint(Math.random() * (bMax - bMin)) + bMin);
}
public static function sinArray(start:int = 255, end:int = 0, cycle:uint = 90):Array {
var f:Function = sinGenerator(start, end, cycle);
var a:Array = [];
for (var i:uint = 0; i < cycle; i++) {
// a.push(f(
}
+ return [];
}
public static function sinGenerator(start:int = 255, end:int = 0, cycle:uint = 90):Function {
var times:uint = 0;
var diff:int = start - end;
var p:Number;
return function():uint {
p = (Math.sin(Math.PI/2 + Math.PI * 2 * (360 / cycle * times) / 360) + 1) / 2;
times++;
if(times >= cycle) times = 0;
return end + (diff * p);
}
}
}
}
diff --git a/src/com/rails2u/utils/ObjectInspecter.as b/src/com/rails2u/utils/ObjectInspecter.as
index 4c4d81b..b7745d5 100644
--- a/src/com/rails2u/utils/ObjectInspecter.as
+++ b/src/com/rails2u/utils/ObjectInspecter.as
@@ -1,57 +1,57 @@
-package com.rails2u.utils
-{
- import flash.utils.getQualifiedClassName;
-
- public class ObjectInspecter
- {
- /*
- *
- */
- public static function inspect(... args):String {
- return inspectImpl(args, false);
- }
-
- internal static function inspectImpl(arg:*, bracket:Boolean = true):String {
- var className:String = getQualifiedClassName(arg);
- var str:String; var results:Array;
-
- switch(getQualifiedClassName(arg)) {
- case 'Object':
- case 'Dictionary':
- results = [];
- for (var key:* in arg) {
- results.push(inspectImpl(key) + ':' + inspectImpl(arg[key], false));
- }
- str = classFormat(className, '{' + results.join(', ') + '}');
- // str = classFormat(className, arg);
- break;
- case 'Array':
- results = [];
- for (var i:uint = 0; i < arg.length; i++) {
- results.push(inspectImpl(arg[i]));
- }
- if (bracket) {
- str = '[' + results.join(', ') + ']';
- } else {
- str = results.join(', ');
- }
- break;
- case 'int':
- case 'uint':
- case 'Number':
- str = arg.toString();
- break;
- case 'String':
- str = arg;
- break;
- default:
- str = classFormat(className, arg);
- }
- return str;
- }
-
- internal static function classFormat(className:String, arg:*):String {
- return '#<' + className + ':' + String(arg) + '>';
- }
- }
-}
\ No newline at end of file
+package com.rails2u.utils
+{
+ import flash.utils.getQualifiedClassName;
+
+ public class ObjectInspecter
+ {
+ /*
+ *
+ */
+ public static function inspect(... args):String {
+ return inspectImpl(args, false);
+ }
+
+ internal static function inspectImpl(arg:*, bracket:Boolean = true):String {
+ var className:String = getQualifiedClassName(arg);
+ var str:String; var results:Array;
+
+ switch(getQualifiedClassName(arg)) {
+ case 'Object':
+ case 'Dictionary':
+ results = [];
+ for (var key:* in arg) {
+ results.push(inspectImpl(key) + ':' + inspectImpl(arg[key], false));
+ }
+ str = classFormat(className, '{' + results.join(', ') + '}');
+ // str = classFormat(className, arg);
+ break;
+ case 'Array':
+ results = [];
+ for (var i:uint = 0; i < arg.length; i++) {
+ results.push(inspectImpl(arg[i]));
+ }
+ if (bracket) {
+ str = '[' + results.join(', ') + ']';
+ } else {
+ str = results.join(', ');
+ }
+ break;
+ case 'int':
+ case 'uint':
+ case 'Number':
+ str = arg.toString();
+ break;
+ case 'String':
+ str = arg;
+ break;
+ default:
+ str = classFormat(className, arg);
+ }
+ return str;
+ }
+
+ internal static function classFormat(className:String, arg:*):String {
+ return '#<' + className + ':' + String(arg) + '>';
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
d6120e4d5c7ca29c768fd376374d6d240e262c2a
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@36 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/swflayer/SWFLayer.as b/src/com/rails2u/swflayer/SWFLayer.as
index c7f8175..46a8132 100644
--- a/src/com/rails2u/swflayer/SWFLayer.as
+++ b/src/com/rails2u/swflayer/SWFLayer.as
@@ -1,115 +1,146 @@
package com.rails2u.swflayer {
import flash.external.ExternalInterface;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
+ import flash.errors.IOError;
public dynamic class SWFLayer extends Proxy {
private static var _instance:SWFLayer;
private static var _style:SWFStyle;
- public function SWFLayer(position:String = 'absolute') {
+ public function SWFLayer() {
if(SWFLayer._instance) throw(new ArgumentError('Please access SWFLayer.getInstance()'));
var x:String = getProperty('offsetTop');
var y:String = getProperty('offsetLeft');
_style = new SWFStyle(this);
this.x = Number(x);
this.y = Number(y);
- this.height = NaN;
- this.width = NaN;
- if(_style.position != position) _style.position = position;
-
- //setStyle('x', x);
- //setStyle('y', y);
- //setStyle('height', SWFLayer.AUTO);
- //setStyle('width', SWFLayer.AUTO);
- //setStyle('position', position);
+ this.height = this.clientHeight;
+ this.width = this.clientWidth;
+ if (_style.position != 'absolute') _style.position = 'absolute';
}
public function get style():SWFStyle {
return _style;
}
public static function getInstance():SWFLayer {
return _instance ||= new SWFLayer();
}
public static function get instance():SWFLayer {
return _instance ||= new SWFLayer();
}
public function set width(value:Number):void {
if (isNaN(value)) {
_style.setStyle('width', SWFStyle.AUTO);
} else {
_style.setStyle('width', value.toString());
}
}
public function get width():Number {
return Number(_style.getStyle('width'));
}
public function set height(value:Number):void {
if (isNaN(value)) {
_style.setStyle('height', SWFStyle.AUTO);
} else {
_style.setStyle('height', value.toString());
}
}
public function get height():Number {
return Number(style.getStyle('height'));
}
public function set x(value:Number):void {
_style.setStyle('left', value.toString());
}
public function get x():Number {
try {
return Number(_style.getStyle('left').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
public function set y(value:Number):void {
_style.setStyle('top', value.toString());
}
public function get y():Number {
try {
return Number(_style.getStyle('top').toString().replace('px', ''));
} catch(e:Error) {}
return 0;
}
+ public function fitInBrowser():void {
+ this.x = this.scrollLeft;
+ this.y = this.scrollTop;
+ this.width = this.browserWidth;
+ this.height = this.browserHeight;
+ }
+
+ public function get browserWidth():Number {
+ //return execExternalIntarface('return document.body.clientWidth') as Number; // IOError ;(
+ return execExternalIntarface('return document.getElementsByTagName("body")[0].clientWidth') as Number;
+ }
+
+ public function get browserHeight():Number {
+ return execExternalIntarface('return document.getElementsByTagName("body")[0].clientHeight') as Number;
+ }
+
+ public function get htmlWidth():Number {
+ return execExternalIntarface('return document.getElementsByTagName("html")[0].clientWidth') as Number;
+ }
+
+ public function get htmlHeight():Number {
+ return execExternalIntarface('return document.getElementsByTagName("html")[0].clientHeight') as Number;
+ }
+
+ public function get scrollTop():Number {
+ return execExternalIntarface('return window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop') as Number;
+ }
+
+ public function get scrollLeft():Number {
+ return execExternalIntarface('return window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft') as Number;
+ }
+
public function get objectID():String {
return ExternalInterface.objectID;
}
+
public function setProperty(name:String, value:String):void {
exec(name + ' = "' + value + '"');
}
public function getProperty(name:String):* {
return exec(name);
}
public function exec(cmd:String):* {
cmd = "return document.getElementById('" + objectID + "')." + cmd;
return execExternalIntarface(cmd);
}
public static function execExternalIntarface(cmd:String):* {
cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
override flash_proxy function setProperty(name:*, value:*):void {
this.setProperty(name, value);
}
override flash_proxy function getProperty(name:*):* {
return this.getProperty(name);
}
+
+ override flash_proxy function callProperty(name:*, ...rest):* {
+ }
}
}
diff --git a/src/com/rails2u/swflayer/SWFStyle.as b/src/com/rails2u/swflayer/SWFStyle.as
new file mode 100644
index 0000000..bbd8c0f
--- /dev/null
+++ b/src/com/rails2u/swflayer/SWFStyle.as
@@ -0,0 +1,30 @@
+package com.rails2u.swflayer {
+ import flash.external.ExternalInterface;
+ import flash.utils.Proxy;
+ import flash.utils.flash_proxy;
+
+ internal dynamic class SWFStyle extends Proxy {
+ public static const AUTO:String = 'auto';
+
+ private var layer:SWFLayer;
+ public function SWFStyle(layer:SWFLayer) {
+ this.layer = layer;
+ }
+
+ public function setStyle(style:String, value:String):void {
+ layer.exec('style.' + style + ' = "' + value + '"');
+ }
+
+ public function getStyle(style:String):* {
+ return layer.exec('style.' + style);
+ }
+
+ override flash_proxy function setProperty(name:*, value:*):void {
+ this.setStyle(name, value);
+ }
+
+ override flash_proxy function getProperty(name:*):* {
+ return this.getStyle(name);
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
50a4303a2e001ad87ce64246e64d5996c3124956
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@35 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/swflayer/SWFLayer.as b/src/com/rails2u/swflayer/SWFLayer.as
index a6b6407..c7f8175 100644
--- a/src/com/rails2u/swflayer/SWFLayer.as
+++ b/src/com/rails2u/swflayer/SWFLayer.as
@@ -1,86 +1,115 @@
package com.rails2u.swflayer {
import flash.external.ExternalInterface;
- public class SWFLayer {
- public static const AUTO:String = 'auto';
- public static function get objectID():String {
- return ExternalInterface.objectID;
- }
+ import flash.utils.Proxy;
+ import flash.utils.flash_proxy;
+
+ public dynamic class SWFLayer extends Proxy {
+ private static var _instance:SWFLayer;
+ private static var _style:SWFStyle;
+ public function SWFLayer(position:String = 'absolute') {
+ if(SWFLayer._instance) throw(new ArgumentError('Please access SWFLayer.getInstance()'));
- public static function initialize(position:String = 'absolute'):void {
var x:String = getProperty('offsetTop');
var y:String = getProperty('offsetLeft');
- setStyle('x', x);
- setStyle('y', y);
- setStyle('height', AUTO);
- setStyle('width', AUTO);
- setStyle('position', position);
+ _style = new SWFStyle(this);
+ this.x = Number(x);
+ this.y = Number(y);
+ this.height = NaN;
+ this.width = NaN;
+ if(_style.position != position) _style.position = position;
+
+ //setStyle('x', x);
+ //setStyle('y', y);
+ //setStyle('height', SWFLayer.AUTO);
+ //setStyle('width', SWFLayer.AUTO);
+ //setStyle('position', position);
}
- public static function set width(value:Number):void {
- if (isNaN(value)) {
- setStyle('width', AUTO);
- } else {
- setStyle('width', value.toString());
- }
+ public function get style():SWFStyle {
+ return _style;
+ }
+
+ public static function getInstance():SWFLayer {
+ return _instance ||= new SWFLayer();
}
- public static function get width():Number {
- return Number(getStyle('width'));
+ public static function get instance():SWFLayer {
+ return _instance ||= new SWFLayer();
}
- public static function set height(value:Number):void {
+ public function set width(value:Number):void {
if (isNaN(value)) {
- setStyle('height', AUTO);
+ _style.setStyle('width', SWFStyle.AUTO);
} else {
- setStyle('height', value.toString());
+ _style.setStyle('width', value.toString());
}
}
- public static function get height():Number {
- return Number(getStyle('height'));
+ public function get width():Number {
+ return Number(_style.getStyle('width'));
}
- public static function set x(value:Number):void {
- setStyle('left', value.toString());
+ public function set height(value:Number):void {
+ if (isNaN(value)) {
+ _style.setStyle('height', SWFStyle.AUTO);
+ } else {
+ _style.setStyle('height', value.toString());
+ }
}
- public static function get x():Number {
- return Number(getStyle('left'));
+ public function get height():Number {
+ return Number(style.getStyle('height'));
}
- public static function set y(value:Number):void {
- setStyle('top', value.toString());
+ public function set x(value:Number):void {
+ _style.setStyle('left', value.toString());
}
- public static function get y():Number {
- return Number(getStyle('top'));
+ public function get x():Number {
+ try {
+ return Number(_style.getStyle('left').toString().replace('px', ''));
+ } catch(e:Error) {}
+ return 0;
}
- public static function layerExec(str:String):* {
- var cmd:String = "return document.getElementById('" + objectID + "')." + str;
- return exec(cmd);
+ public function set y(value:Number):void {
+ _style.setStyle('top', value.toString());
}
- public static function setProperty(name:String, value:String):void {
- layerExec(name + ' = "' + value + '"');
+ public function get y():Number {
+ try {
+ return Number(_style.getStyle('top').toString().replace('px', ''));
+ } catch(e:Error) {}
+ return 0;
}
- public static function getProperty(name:String):* {
- return layerExec(name);
+ public function get objectID():String {
+ return ExternalInterface.objectID;
+ }
+ public function setProperty(name:String, value:String):void {
+ exec(name + ' = "' + value + '"');
}
- public static function setStyle(style:String, value:String):void {
- layerExec('style.' + style + ' = "' + value + '"');
+ public function getProperty(name:String):* {
+ return exec(name);
}
- public static function getStyle(style:String):* {
- return layerExec('style.' + style);
+ public function exec(cmd:String):* {
+ cmd = "return document.getElementById('" + objectID + "')." + cmd;
+ return execExternalIntarface(cmd);
}
- public static function exec(cmd:String):* {
- var cmd:String = "(function() {" + cmd + ";})()";
- log(cmd);
+ public static function execExternalIntarface(cmd:String):* {
+ cmd = "(function() {" + cmd + ";})";
return ExternalInterface.call(cmd);
}
+
+ override flash_proxy function setProperty(name:*, value:*):void {
+ this.setProperty(name, value);
+ }
+
+ override flash_proxy function getProperty(name:*):* {
+ return this.getProperty(name);
+ }
}
}
|
hotchpotch/as3rails2u
|
9df9716e160419180543bee89d5f1c2887610acc
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@34 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/swflayer/SWFLayer.as b/src/com/rails2u/swflayer/SWFLayer.as
new file mode 100644
index 0000000..a6b6407
--- /dev/null
+++ b/src/com/rails2u/swflayer/SWFLayer.as
@@ -0,0 +1,86 @@
+package com.rails2u.swflayer {
+ import flash.external.ExternalInterface;
+ public class SWFLayer {
+ public static const AUTO:String = 'auto';
+ public static function get objectID():String {
+ return ExternalInterface.objectID;
+ }
+
+ public static function initialize(position:String = 'absolute'):void {
+ var x:String = getProperty('offsetTop');
+ var y:String = getProperty('offsetLeft');
+ setStyle('x', x);
+ setStyle('y', y);
+ setStyle('height', AUTO);
+ setStyle('width', AUTO);
+ setStyle('position', position);
+ }
+
+ public static function set width(value:Number):void {
+ if (isNaN(value)) {
+ setStyle('width', AUTO);
+ } else {
+ setStyle('width', value.toString());
+ }
+ }
+
+ public static function get width():Number {
+ return Number(getStyle('width'));
+ }
+
+ public static function set height(value:Number):void {
+ if (isNaN(value)) {
+ setStyle('height', AUTO);
+ } else {
+ setStyle('height', value.toString());
+ }
+ }
+
+ public static function get height():Number {
+ return Number(getStyle('height'));
+ }
+
+ public static function set x(value:Number):void {
+ setStyle('left', value.toString());
+ }
+
+ public static function get x():Number {
+ return Number(getStyle('left'));
+ }
+
+ public static function set y(value:Number):void {
+ setStyle('top', value.toString());
+ }
+
+ public static function get y():Number {
+ return Number(getStyle('top'));
+ }
+
+ public static function layerExec(str:String):* {
+ var cmd:String = "return document.getElementById('" + objectID + "')." + str;
+ return exec(cmd);
+ }
+
+ public static function setProperty(name:String, value:String):void {
+ layerExec(name + ' = "' + value + '"');
+ }
+
+ public static function getProperty(name:String):* {
+ return layerExec(name);
+ }
+
+ public static function setStyle(style:String, value:String):void {
+ layerExec('style.' + style + ' = "' + value + '"');
+ }
+
+ public static function getStyle(style:String):* {
+ return layerExec('style.' + style);
+ }
+
+ public static function exec(cmd:String):* {
+ var cmd:String = "(function() {" + cmd + ";})()";
+ log(cmd);
+ return ExternalInterface.call(cmd);
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
ac09e07c9213ca1f648b6cc97cfa171778840ba7
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@33 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/net/navigateToURL.as b/src/com/rails2u/net/navigateToURL.as
index 6292527..a34a6b3 100644
--- a/src/com/rails2u/net/navigateToURL.as
+++ b/src/com/rails2u/net/navigateToURL.as
@@ -1,41 +1,50 @@
package com.rails2u.net {
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.net.navigateToURL;
import flash.external.ExternalInterface;
+ import com.rails2u.utils.Browser;
/*
* Popup a window through popup blockers.
* Base by http://d.hatena.ne.jp/os0x/20070812/1186941620
*/
public function navigateToURL(request:URLRequest, windows:String = ''):void {
if (windows == '_self') flash.net.navigateToURL(request, '_self');
-
- var url:String = request.url;
- if (request.method == URLRequestMethod.GET) {
- var uv:URLVariables = request.data as URLVariables;
- if (!uv) {
- uv = new URLVariables;
- for (var key:String in request.data) {
- uv[key] = request.data[key];
+ var browser:String = Browser.browser;
+
+ if (browser == Browser.FIREFOX || browser == Browser.MSIE) {
+ var url:String = request.url;
+ if (request.method == URLRequestMethod.GET) {
+ var uv:URLVariables = request.data as URLVariables;
+ if (!uv) {
+ uv = new URLVariables;
+ for (var key:String in request.data) {
+ uv[key] = request.data[key];
+ }
+ }
+ var query:String = uv.toString();
+ if (query.length > 0) {
+ url += '?' + query;
}
}
- var query:String = uv.toString();
- if (query.length > 0) {
- url += '?' + query;
- }
- }
-
- var res:String = ExternalInterface.call(
- 'function(url, tg){return window.GeckoActiveXObject ? window.open(url, tg) : null;}',
- url, windows
- );
- if (!res) {
- var jsURL:String = 'javascript:(function(){window.open("' + url + '", "' + windows + '")})();'
- var req:URLRequest = new URLRequest(jsURL);
- flash.net.navigateToURL(req, '_self');
+ if (browser == Browser.FIREFOX) {
+ // FIREFOX
+ var res:String = ExternalInterface.call(
+ 'function(url, tg){return window.open(url, tg);}',
+ url, windows
+ );
+ } else {
+ // IE
+ var jsURL:String = 'javascript:(function(){window.open("' + url + '", "' + windows + '")})();'
+ var req:URLRequest = new URLRequest(jsURL);
+ flash.net.navigateToURL(req, windows);
+ }
+ } else {
+ // Opera, Safari
+ flash.net.navigateToURL(request, windows);
}
}
}
diff --git a/src/com/rails2u/utils/Browser.as b/src/com/rails2u/utils/Browser.as
new file mode 100644
index 0000000..b773533
--- /dev/null
+++ b/src/com/rails2u/utils/Browser.as
@@ -0,0 +1,49 @@
+package com.rails2u.utils {
+ import flash.external.ExternalInterface;
+
+ public class Browser {
+ public static const FIREFOX:String = 'firefox';
+ public static const MSIE:String = 'msie';
+ public static const OPERA:String = 'opera';
+ public static const SAFARI:String = 'safari';
+ public static const UNKNOWN:String = 'unknown';
+
+ private static var _loaded:Boolean = false;
+ private static function init():void {
+ if (!_loaded) {
+ _loaded = true;
+ setUserAgent();
+ setBrowser();
+ }
+ }
+
+ public static function get userAgent():String {
+ init();
+ return _userAgent;
+ }
+
+ public static function get browser():String {
+ init();
+ return _browser;
+ }
+
+ private static var _userAgent:String;
+ private static function setUserAgent():void {
+ _userAgent = String(ExternalInterface.call('function() {return navigator.userAgent;}'));
+ }
+
+ private static var _browser:String = UNKNOWN;
+ private static function setBrowser():void {
+ var tmp:String = _userAgent.toUpperCase();
+ if (tmp.indexOf('FIREFOX') >= 0) {
+ _browser = FIREFOX;
+ } else if(tmp.indexOf('SAFARI') >= 0) {
+ _browser = SAFARI;
+ } else if(tmp.indexOf('OPERA') >= 0) {
+ _browser = OPERA;
+ } else if(tmp.indexOf('MSIE') >= 0) {
+ _browser = MSIE
+ }
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
cce2155bdb3c3f53b5dd595f5d54b2812bb3c5fe
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@32 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/net/navigateToURL.as b/src/com/rails2u/net/navigateToURL.as
index f6b5b9a..6292527 100644
--- a/src/com/rails2u/net/navigateToURL.as
+++ b/src/com/rails2u/net/navigateToURL.as
@@ -1,41 +1,41 @@
package com.rails2u.net {
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.net.navigateToURL;
import flash.external.ExternalInterface;
/*
* Popup a window through popup blockers.
* Base by http://d.hatena.ne.jp/os0x/20070812/1186941620
*/
public function navigateToURL(request:URLRequest, windows:String = ''):void {
if (windows == '_self') flash.net.navigateToURL(request, '_self');
var url:String = request.url;
if (request.method == URLRequestMethod.GET) {
var uv:URLVariables = request.data as URLVariables;
if (!uv) {
uv = new URLVariables;
for (var key:String in request.data) {
uv[key] = request.data[key];
}
}
var query:String = uv.toString();
if (query.length > 0) {
url += '?' + query;
}
}
var res:String = ExternalInterface.call(
'function(url, tg){return window.GeckoActiveXObject ? window.open(url, tg) : null;}',
url, windows
);
if (!res) {
- var jsURL:String = 'javascript:window.open("' + url + '","' + windows + '");void(0);';
+ var jsURL:String = 'javascript:(function(){window.open("' + url + '", "' + windows + '")})();'
var req:URLRequest = new URLRequest(jsURL);
flash.net.navigateToURL(req, '_self');
}
}
}
|
hotchpotch/as3rails2u
|
e28f2abee1428e0eb4d4a4c881cdd58e7184fedf
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@31 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/net/navigateToURL.as b/src/com/rails2u/net/navigateToURL.as
new file mode 100644
index 0000000..f6b5b9a
--- /dev/null
+++ b/src/com/rails2u/net/navigateToURL.as
@@ -0,0 +1,41 @@
+package com.rails2u.net {
+ import flash.net.URLRequest;
+ import flash.net.URLRequestMethod;
+ import flash.net.URLVariables;
+ import flash.net.navigateToURL;
+ import flash.external.ExternalInterface;
+
+ /*
+ * Popup a window through popup blockers.
+ * Base by http://d.hatena.ne.jp/os0x/20070812/1186941620
+ */
+ public function navigateToURL(request:URLRequest, windows:String = ''):void {
+ if (windows == '_self') flash.net.navigateToURL(request, '_self');
+
+ var url:String = request.url;
+ if (request.method == URLRequestMethod.GET) {
+ var uv:URLVariables = request.data as URLVariables;
+ if (!uv) {
+ uv = new URLVariables;
+ for (var key:String in request.data) {
+ uv[key] = request.data[key];
+ }
+ }
+ var query:String = uv.toString();
+ if (query.length > 0) {
+ url += '?' + query;
+ }
+ }
+
+ var res:String = ExternalInterface.call(
+ 'function(url, tg){return window.GeckoActiveXObject ? window.open(url, tg) : null;}',
+ url, windows
+ );
+
+ if (!res) {
+ var jsURL:String = 'javascript:window.open("' + url + '","' + windows + '");void(0);';
+ var req:URLRequest = new URLRequest(jsURL);
+ flash.net.navigateToURL(req, '_self');
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
4d160b5521af29895780a44c7b94777af1b6fa1d
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@30 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/d_project/qrcode/BitBuffer.as b/src/com/d_project/qrcode/BitBuffer.as
deleted file mode 100644
index 7ed3114..0000000
--- a/src/com/d_project/qrcode/BitBuffer.as
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * BitBuffer
- * @author Kazuhiko Arase
- */
- internal class BitBuffer {
-
- private var buffer : Array;
-
- private var length : int;
-
- public function BitBuffer() {
- buffer = new Array();
- length = 0;
- }
-
- public function getBuffer() : Array {
- return buffer;
- }
-
- public function getLengthInBits() : int {
- return length;
- }
-
- private function getBitAt(index : int) : Boolean {
- return ( (buffer[Math.floor(index / 8)] >>> (7 - index % 8) ) & 1) == 1;
- }
-
- public function put(num : int, length : int) : void {
- for (var i : int = 0; i < length; i++) {
- putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
- }
- }
-
- public function putBit(bit : Boolean) : void {
-
- if (length == buffer.length * 8) {
- buffer.push(0);
- }
-
- if (bit) {
- buffer[Math.floor(length / 8)] |= (0x80 >>> (length % 8) );
- }
-
- length++;
- }
-
- public function toString() : String {
- var buffer : String = "";
- for (var i : int = 0; i < getLengthInBits(); i++) {
- buffer += (getBitAt(i)? '1' : '0');
- }
- return buffer;
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/ErrorCorrectLevel.as b/src/com/d_project/qrcode/ErrorCorrectLevel.as
deleted file mode 100644
index 7061604..0000000
--- a/src/com/d_project/qrcode/ErrorCorrectLevel.as
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * 誤ãè¨æ£ã¬ãã«.
- * @author Kazuhiko Arase
- */
- public class ErrorCorrectLevel {
-
- /**
- * 復å
è½å 7%.
- * <br>vodafoneã§ä½¿ç¨ä¸å¯?
- */
- public static const L : int = 1;
-
- /**
- * 復å
è½å 15%.
- */
- public static const M : int = 0;
-
- /**
- * 復å
è½å 25%.
- */
- public static const Q : int = 3;
-
- /**
- * 復å
è½å 30%.
- */
- public static const H : int = 2;
-
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/MaskPattern.as b/src/com/d_project/qrcode/MaskPattern.as
deleted file mode 100644
index 2d177c9..0000000
--- a/src/com/d_project/qrcode/MaskPattern.as
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³.
- * @author Kazuhiko Arase
- */
- internal class MaskPattern {
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³000
- */
- public static const PATTERN000 : int = 0;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³001
- */
- public static const PATTERN001 : int = 1;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³010
- */
- public static const PATTERN010 : int = 2;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³011
- */
- public static const PATTERN011 : int = 3;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³100
- */
- public static const PATTERN100 : int = 4;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³101
- */
- public static const PATTERN101 : int = 5;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³110
- */
- public static const PATTERN110 : int = 6;
-
- /**
- * ãã¹ã¯ãã¿ã¼ã³111
- */
- public static const PATTERN111 : int = 7;
-
- }
-
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/Mode.as b/src/com/d_project/qrcode/Mode.as
deleted file mode 100644
index 9a36633..0000000
--- a/src/com/d_project/qrcode/Mode.as
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * ã¢ã¼ã.
- * @author Kazuhiko Arase
- */
- public class Mode {
-
- /**
- * èªåã¢ã¼ã
- */
- public static const MODE_AUTO : int = 0;
-
- /**
- * æ°å¤ã¢ã¼ã
- */
- public static const MODE_NUMBER : int = 1 << 0;
-
- /**
- * è±æ°åã¢ã¼ã
- */
- public static const MODE_ALPHA_NUM : int = 1 << 1;
-
- /**
- * 8ããããã¤ãã¢ã¼ã
- */
- public static const MODE_8BIT_BYTE : int = 1 << 2;
-
- /**
- * æ¼¢åã¢ã¼ã
- */
- public static const MODE_KANJI : int = 1 << 3;
-
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/Polynomial.as b/src/com/d_project/qrcode/Polynomial.as
deleted file mode 100644
index e9191bf..0000000
--- a/src/com/d_project/qrcode/Polynomial.as
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * Polynomial
- * @author Kazuhiko Arase
- */
- internal class Polynomial {
-
- private var num : Array;
-
- public function Polynomial(num : Array, shift : int = 0) {
-
- var offset : int = 0;
-
- while (offset < num.length && num[offset] == 0) {
- offset++;
- }
-
- this.num = new Array(num.length - offset + shift);
- for (var i : int = 0; i < num.length - offset; i++) {
- this.num[i] = num[offset + i];
- }
- }
-
- public function getAt(index : int) : int {
- return num[index];
- }
-
- public function getLength() : int {
- return num.length;
- }
-
- public function toString() : String {
-
- var buffer : String = "";
-
- for (var i : int = 0; i < getLength(); i++) {
- if (i > 0) {
- buffer += ",";
- }
- buffer += getAt(i);
- }
-
- return buffer;
- }
-
- public function toLogString() : String {
-
- var buffer : String = "";
-
- for (var i : int = 0; i < getLength(); i++) {
- if (i > 0) {
- buffer += ",";
- }
- buffer += QRMath.glog(getAt(i) );
-
- }
-
- return buffer.toString();
- }
-
- public function multiply(e : Polynomial) : Polynomial {
-
- var num : Array = new Array(getLength() + e.getLength() - 1);
-
- for (var i : int = 0; i < getLength(); i++) {
- for (var j : int = 0; j < e.getLength(); j++) {
- num[i + j] ^= QRMath.gexp(QRMath.glog(getAt(i) ) + QRMath.glog(e.getAt(j) ) );
- }
- }
-
- return new Polynomial(num);
- }
-
- public function mod(e : Polynomial) : Polynomial {
-
- if (getLength() - e.getLength() < 0) {
- return this;
- }
-
- // æä¸ä½æ¡ã®æ¯ç
- var ratio : int = QRMath.glog(getAt(0) ) - QRMath.glog(e.getAt(0) );
-
- var i : int;
-
- // ã³ãã¼ä½æ
- var num : Array = new Array(getLength() );
- for (i = 0; i < getLength(); i++) {
- num[i] = getAt(i);
- }
-
- // å¼ãç®ãã¦ä½ããè¨ç®
- for (i = 0; i < e.getLength(); i++) {
- num[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i) ) + ratio);
- }
-
- // å帰è¨ç®
- return new Polynomial(num).mod(e);
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QR8BitByte.as b/src/com/d_project/qrcode/QR8BitByte.as
deleted file mode 100644
index 02b019e..0000000
--- a/src/com/d_project/qrcode/QR8BitByte.as
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.d_project.qrcode {
-
- import flash.utils.ByteArray;
-
- /**
- * QR8BitByte
- * @author Kazuhiko Arase
- */
- internal class QR8BitByte extends QRData {
-
- public function QR8BitByte(data : String) {
- super(Mode.MODE_8BIT_BYTE, data);
- }
-
- public override function write(buffer : BitBuffer) : void {
- var data : ByteArray = StringUtil.getBytes(getData(), QRUtil.getJISEncoding() );
- for (var i : int = 0; i < data.length; i++) {
- buffer.put(data[i], 8);
- }
- }
-
- public override function getLength() : int {
- return StringUtil.getBytes(getData(), QRUtil.getJISEncoding() ).length;
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRAlphaNum.as b/src/com/d_project/qrcode/QRAlphaNum.as
deleted file mode 100644
index cd4e86b..0000000
--- a/src/com/d_project/qrcode/QRAlphaNum.as
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * QRAlphaNum
- * @author Kazuhiko Arase
- */
- internal class QRAlphaNum extends QRData {
-
- public function QRAlphaNum(data : String) {
- super(Mode.MODE_ALPHA_NUM, data);
- }
-
- public override function write(buffer : BitBuffer) : void {
-
- var i : int = 0;
- var s : String = getData();
-
- while (i + 1 < s.length) {
- buffer.put(getCode(s.charAt(i) ) * 45 + getCode(s.charAt(i + 1) ), 11);
- i += 2;
- }
-
- if (i < s.length) {
- buffer.put(getCode(s.charAt(i) ), 6);
- }
- }
-
- public override function getLength() : int {
- return getData().length;
- }
-
- private static function getCode(c : String) : int {
- var code : int = c.charCodeAt(0);
- if (getCharCode('0') <= code && code <= getCharCode('9') ) {
- return code - getCharCode('0');
- } else if (getCharCode('A') <= code && code <= getCharCode('Z') ) {
- return code - getCharCode('A') + 10;
- } else {
- switch (c) {
- case ' ' : return 36;
- case '$' : return 37;
- case '%' : return 38;
- case '*' : return 39;
- case '+' : return 40;
- case '-' : return 41;
- case '.' : return 42;
- case '/' : return 43;
- case ':' : return 44;
- default :
- throw new Error("illegal char :" + c);
- }
- }
- throw new Error();
- }
-
- private static function getCharCode(c : String) : int {
- return c.charCodeAt(0);
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRCode.as b/src/com/d_project/qrcode/QRCode.as
deleted file mode 100644
index a72e5d1..0000000
--- a/src/com/d_project/qrcode/QRCode.as
+++ /dev/null
@@ -1,550 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * QRã³ã¼ã.
- * <br/>
- * â ä½¿ãæ¹
- * <ul>
- * <li>誤ãè¨æ£ã¬ãã«ããã¼ã¿çã諸ãã©ã¡ã¼ã¿ãè¨å®ãã¾ãã</li>
- * <li>make() ãå¼ã³åºãã¦QRã³ã¼ãã使ãã¾ãã</li>
- * <li>getModuleCount() 㨠isDark() ã§ãQRã³ã¼ãã®ãã¼ã¿ãåå¾ãã¾ãã</li>
- * </ul>
- * @author Kazuhiko Arase
- */
- public class QRCode {
-
- private static const PAD0 : int = 0xEC;
-
- private static const PAD1 : int = 0x11;
-
- private var typeNumber : int;
-
- private var modules : Array;
-
- private var moduleCount : int;
-
- private var errorCorrectLevel : int;
-
- private var qrDataList : Array;
-
- /**
- * ã³ã³ã¹ãã©ã¯ã¿
- * <br>åçª1, 誤ãè¨æ£ã¬ãã«H ã®QRã³ã¼ãã®ã¤ã³ã¹ã¿ã³ã¹ãçæãã¾ãã
- * @see ErrorCorrectLevel
- */
- public function QRCode() {
- this.typeNumber = 1;
- this.errorCorrectLevel = ErrorCorrectLevel.H;
- this.qrDataList = new Array();
- }
-
- /**
- * åçªãåå¾ããã
- * @return åçª
- */
- public function getTypeNumber() : int {
- return typeNumber;
- }
-
- /**
- * åçªãè¨å®ããã
- * @param typeNumber åçª
- */
- public function setTypeNumber(typeNumber : int) : void {
- this.typeNumber = typeNumber;
- }
-
- /**
- * 誤ãè¨æ£ã¬ãã«ãåå¾ããã
- * @return 誤ãè¨æ£ã¬ãã«
- * @see ErrorCorrectLevel
- */
- public function getErrorCorrectLevel() : int {
- return errorCorrectLevel;
- }
-
- /**
- * 誤ãè¨æ£ã¬ãã«ãè¨å®ããã
- * @param errorCorrectLevel 誤ãè¨æ£ã¬ãã«
- * @see ErrorCorrectLevel
- */
- public function setErrorCorrectLevel(errorCorrectLevel : int) : void {
- this.errorCorrectLevel = errorCorrectLevel;
- }
-
- /**
- * ã¢ã¼ããæå®ãã¦ãã¼ã¿ã追å ããã
- * @param data ãã¼ã¿
- * @param mode ã¢ã¼ã
- * @see Mode
- */
- public function addData(data : String, mode : int = 0) : void {
-
- if (mode == Mode.MODE_AUTO) {
- mode = QRUtil.getMode(data);
- }
-
- switch(mode) {
-
- case Mode.MODE_NUMBER :
- addQRData(new QRNumber(data) );
- break;
-
- case Mode.MODE_ALPHA_NUM :
- addQRData(new QRAlphaNum(data) );
- break;
-
- case Mode.MODE_8BIT_BYTE :
- addQRData(new QR8BitByte(data) );
- break;
-
- case Mode.MODE_KANJI :
- addQRData(new QRKanji(data) );
- break;
-
- default :
- throw new Error("mode:" + mode);
- }
- }
-
- /**
- * ãã¼ã¿ãã¯ãªã¢ããã
- * <br/>addData ã§è¿½å ããããã¼ã¿ãã¯ãªã¢ãã¾ãã
- */
- public function clearData() : void {
- qrDataList = new Array();
- }
-
- private function addQRData(qrData : QRData) : void {
- qrDataList.push(qrData);
- }
-
- private function getQRDataCount() : int {
- return qrDataList.length;
- }
-
- private function getQRData(index : int) : QRData {
- return qrDataList[index];
- }
-
- /**
- * æã¢ã¸ã¥ã¼ã«ãã©ãããåå¾ããã
- * @param row è¡ (0 ï½ ã¢ã¸ã¥ã¼ã«æ° - 1)
- * @param col å (0 ï½ ã¢ã¸ã¥ã¼ã«æ° - 1)
- */
- public function isDark(row : int, col : int) : Boolean {
- if (modules[row][col] != null) {
- return modules[row][col];
- } else {
- return false;
- }
- }
-
- /**
- * ã¢ã¸ã¥ã¼ã«æ°ãåå¾ããã
- */
- public function getModuleCount() : int {
- return moduleCount;
- }
-
- /**
- * QRã³ã¼ãã使ããã
- */
- public function make() : void {
- makeImpl(false, getBestMaskPattern() );
- }
-
- private function getBestMaskPattern() : int {
-
- var minLostPoint : int = 0;
- var pattern : int = 0;
-
- for (var i : int = 0; i < 8; i++) {
-
- makeImpl(true, i);
-
- var lostPoint : int = QRUtil.getLostPoint(this);
-
- if (i == 0 || minLostPoint > lostPoint) {
- minLostPoint = lostPoint;
- pattern = i;
- }
- }
-
- return pattern;
- }
-
- /**
- *
- */
- private function makeImpl(test : Boolean, maskPattern : int) : void {
-
- // ã¢ã¸ã¥ã¼ã«åæå
- moduleCount = typeNumber * 4 + 17;
- modules = new Array(moduleCount);
- for (var i : int = 0; i < moduleCount; i++) {
- modules[i] = new Array(moduleCount);
- }
-
- // ä½ç½®æ¤åºãã¿ã¼ã³åã³åé¢ãã¿ã¼ã³ãè¨å®
- setupPositionProbePattern(0, 0);
- setupPositionProbePattern(moduleCount - 7, 0);
- setupPositionProbePattern(0, moduleCount - 7);
-
- setupPositionAdjustPattern();
- setupTimingPattern();
-
- setupTypeInfo(test, maskPattern);
-
- if (typeNumber >= 7) {
- setupTypeNumber(test);
- }
-
- var dataArray : Array = qrDataList;
- var data : Array = createData(typeNumber, errorCorrectLevel, dataArray);
-
- mapData(data, maskPattern);
- }
-
- private function mapData(data : Array, maskPattern : int) : void {
-
- var inc : int = -1;
- var row : int = moduleCount - 1;
- var bitIndex : int = 7;
- var byteIndex : int = 0;
-
- for (var col : int = moduleCount - 1; col > 0; col -= 2) {
-
- if (col == 6) col--;
-
- while (true) {
-
- for (var c : int = 0; c < 2; c++) {
-
- if (modules[row][col - c] == null) {
-
- var dark : Boolean = false;
-
- if (byteIndex < data.length) {
- dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1);
- }
-
- var mask : Boolean = QRUtil.getMask(maskPattern, row, col - c);
-
- if (mask) {
- dark = !dark;
- }
-
- modules[row][col - c] = (dark);
- bitIndex--;
-
- if (bitIndex == -1) {
- byteIndex++;
- bitIndex = 7;
- }
- }
- }
-
- row += inc;
-
- if (row < 0 || moduleCount <= row) {
- row -= inc;
- inc = -inc;
- break;
- }
- }
- }
-
- }
-
- /**
- * ä½ç½®åãããã¿ã¼ã³ãè¨å®
- */
- private function setupPositionAdjustPattern() : void {
-
- var pos : Array = QRUtil.getPatternPosition(typeNumber);
-
- for (var i : int = 0; i < pos.length; i++) {
-
- for (var j : int = 0; j < pos.length; j++) {
-
- var row : int = pos[i];
- var col : int = pos[j];
-
- if (modules[row][col] != null) {
- continue;
- }
-
- for (var r : int = -2; r <= 2; r++) {
-
- for (var c : int = -2; c <= 2; c++) {
-
- if (r == -2 || r == 2 || c == -2 || c == 2
- || (r == 0 && c == 0) ) {
- modules[row + r][col + c] = (true);
- } else {
- modules[row + r][col + c] = (false);
- }
- }
- }
-
- }
- }
- }
-
- /**
- * ä½ç½®æ¤åºãã¿ã¼ã³ãè¨å®
- */
- private function setupPositionProbePattern(row : int, col : int) : void {
-
- for (var r : int = -1; r <= 7; r++) {
-
- for (var c : int = -1; c <= 7; c++) {
-
- if (row + r <= -1 || moduleCount <= row + r
- || col + c <= -1 || moduleCount <= col + c) {
- continue;
- }
-
- if ( (0 <= r && r <= 6 && (c == 0 || c == 6) )
- || (0 <= c && c <= 6 && (r == 0 || r == 6) )
- || (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
- modules[row + r][col + c] = (true);
- } else {
- modules[row + r][col + c] = (false);
- }
- }
- }
- }
-
- /**
- * ã¿ã¤ãã³ã°ãã¿ã¼ã³ãè¨å®
- */
- private function setupTimingPattern() : void {
- for (var r : int = 8; r < moduleCount - 8; r++) {
- if (modules[r][6] != null) {
- continue;
- }
- modules[r][6] = (r % 2 == 0);
- }
- for (var c : int = 8; c < moduleCount - 8; c++) {
- if (modules[6][c] != null) {
- continue;
- }
- modules[6][c] = (c % 2 == 0);
- }
- }
-
- /**
- * åçªãè¨å®
- */
- private function setupTypeNumber(test : Boolean) : void {
-
- var bits : int = QRUtil.getBCHTypeNumber(typeNumber);
- var i : int;
- var mod : Boolean;
-
- for (i = 0; i < 18; i++) {
- mod = (!test && ( (bits >> i) & 1) == 1);
- modules[Math.floor(i / 3)][i % 3 + moduleCount - 8 - 3] = mod;
- }
-
- for (i = 0; i < 18; i++) {
- mod = (!test && ( (bits >> i) & 1) == 1);
- modules[i % 3 + moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
- }
- }
-
- /**
- * 形弿
å ±ãè¨å®
- */
- private function setupTypeInfo(test : Boolean, maskPattern : int) : void {
-
- var data : int = (errorCorrectLevel << 3) | maskPattern;
- var bits : int = QRUtil.getBCHTypeInfo(data);
- var i : int;
- var mod : Boolean;
-
- // 縦æ¹å
- for (i = 0; i < 15; i++) {
-
- mod = (!test && ( (bits >> i) & 1) == 1);
-
- if (i < 6) {
- modules[i][8] = mod;
- } else if (i < 8) {
- modules[i + 1][8] = mod;
- } else {
- modules[moduleCount - 15 + i][8] = mod;
- }
- }
-
- // 横æ¹å
- for (i = 0; i < 15; i++) {
-
- mod = (!test && ( (bits >> i) & 1) == 1);
-
- if (i < 8) {
- modules[8][moduleCount - i - 1] = mod;
- } else if (i < 9) {
- modules[8][15 - i - 1 + 1] = mod;
- } else {
- modules[8][15 - i - 1] = mod;
- }
- }
-
- // åºå®
- modules[moduleCount - 8][8] = (!test);
-
- }
-
- private static function createData(typeNumber : int, errorCorrectLevel : int, dataArray : Array) : Array {
-
- var rsBlocks : Array = RSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
- var buffer : BitBuffer = new BitBuffer();
- var i : int;
-
- for (i = 0; i < dataArray.length; i++) {
- var data : QRData = dataArray[i];
- buffer.put(data.getMode(), 4);
- buffer.put(data.getLength(), data.getLengthInBits(typeNumber) );
- data.write(buffer);
- }
-
- // æå¤§ãã¼ã¿æ°ãè¨ç®
- var totalDataCount : int = 0;
- for (i = 0; i < rsBlocks.length; i++) {
- totalDataCount += rsBlocks[i].getDataCount();
- }
-
- if (buffer.getLengthInBits() > totalDataCount * 8) {
- throw new Error("code length overflow. ("
- + buffer.getLengthInBits()
- + ">"
- + totalDataCount * 8
- + ")");
- }
-
- // çµç«¯ã³ã¼ã
- if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
- buffer.put(0, 4);
- }
-
- // padding
- while (buffer.getLengthInBits() % 8 != 0) {
- buffer.putBit(false);
- }
-
- // padding
- while (true) {
-
- if (buffer.getLengthInBits() >= totalDataCount * 8) {
- break;
- }
- buffer.put(PAD0, 8);
-
- if (buffer.getLengthInBits() >= totalDataCount * 8) {
- break;
- }
- buffer.put(PAD1, 8);
- }
-
- return createBytes(buffer, rsBlocks);
- }
-
- private static function createBytes(buffer : BitBuffer, rsBlocks : Array) : Array {
-
- var offset : int = 0;
-
- var maxDcCount : int = 0;
- var maxEcCount : int = 0;
-
- var dcdata : Array = new Array(rsBlocks.length);
- var ecdata : Array = new Array(rsBlocks.length);
-
- var i : int;
- var r : int;
-
- for (r = 0; r < rsBlocks.length; r++) {
-
- var dcCount : int = rsBlocks[r].getDataCount();
- var ecCount : int = rsBlocks[r].getTotalCount() - dcCount;
-
- maxDcCount = Math.max(maxDcCount, dcCount);
- maxEcCount = Math.max(maxEcCount, ecCount);
-
- dcdata[r] = new Array(dcCount);
- for (i = 0; i < dcdata[r].length; i++) {
- dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset];
- }
- offset += dcCount;
-
- var rsPoly : Polynomial = QRUtil.getErrorCorrectPolynomial(ecCount);
- var rawPoly : Polynomial = new Polynomial(dcdata[r], rsPoly.getLength() - 1);
-
- var modPoly : Polynomial = rawPoly.mod(rsPoly);
- ecdata[r] = new Array(rsPoly.getLength() - 1);
- for (i = 0; i < ecdata[r].length; i++) {
- var modIndex : int = i + modPoly.getLength() - ecdata[r].length;
- ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0;
- }
-
- }
-
- var totalCodeCount : int = 0;
- for (i = 0; i < rsBlocks.length; i++) {
- totalCodeCount += rsBlocks[i].getTotalCount();
- }
-
- var data : Array = new Array(totalCodeCount);
-
- var index : int = 0;
-
- for (i = 0; i < maxDcCount; i++) {
- for (r = 0; r < rsBlocks.length; r++) {
- if (i < dcdata[r].length) {
- data[index++] = dcdata[r][i];
- }
- }
- }
-
- for (i = 0; i < maxEcCount; i++) {
- for (r = 0; r < rsBlocks.length; r++) {
- if (i < ecdata[r].length) {
- data[index++] = ecdata[r][i];
- }
- }
- }
-
- return data;
-
- }
-
- /**
- * æå°ã®åçªã¨ãªã QRCode ã使ããã
- * @param data ãã¼ã¿
- * @param errorCorrectLevel 誤ãè¨æ£ã¬ãã«
- */
- public static function getMinimumQRCode(data : String, errorCorrectLevel : int) : QRCode {
-
- var mode : int = QRUtil.getMode(data);
-
- var qr : QRCode = new QRCode();
- qr.setErrorCorrectLevel(errorCorrectLevel);
- qr.addData(data, mode);
-
- var length : int = qr.getQRData(0).getLength();
-
- for (var typeNumber : int = 1; typeNumber <= 10; typeNumber++) {
- if (length <= QRUtil.getMaxLength(typeNumber, mode, errorCorrectLevel) ) {
- qr.setTypeNumber(typeNumber);
- break;
- }
- }
-
- qr.make();
-
- return qr;
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRData.as b/src/com/d_project/qrcode/QRData.as
deleted file mode 100644
index 88f34bf..0000000
--- a/src/com/d_project/qrcode/QRData.as
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * QRData
- * @author Kazuhiko Arase
- */
- internal class QRData {
-
- private var mode : int;
-
- private var data : String;
-
- public function QRData(mode : int, data : String) {
- this.mode = mode;
- this.data = data;
- }
-
- public function getMode() : int {
- return mode;
- }
-
- public function getData() : String {
- return data;
- }
-
- public function getLength() : int {
- throw new Error("not implemented.");
- }
-
- public function write(buffer : BitBuffer) : void {
- throw new Error("not implemented.");
- }
-
- /**
- * åçªåã³ã¢ã¼ãã«å¯¾ãããããé·ãåå¾ããã
- */
- public function getLengthInBits(type : int) : int {
-
- if (1 <= type && type < 10) {
-
- // 1 - 9
-
- switch(mode) {
- case Mode.MODE_NUMBER : return 10;
- case Mode.MODE_ALPHA_NUM : return 9;
- case Mode.MODE_8BIT_BYTE : return 8;
- case Mode.MODE_KANJI : return 8;
- default :
- throw new Error("mode:" + mode);
- }
-
- } else if (type < 27) {
-
- // 10 - 26
-
- switch(mode) {
- case Mode.MODE_NUMBER : return 12;
- case Mode.MODE_ALPHA_NUM : return 11;
- case Mode.MODE_8BIT_BYTE : return 16;
- case Mode.MODE_KANJI : return 10;
- default :
- throw new Error("mode:" + mode);
- }
-
- } else if (type < 41) {
-
- // 27 - 40
-
- switch(mode) {
- case Mode.MODE_NUMBER : return 14;
- case Mode.MODE_ALPHA_NUM : return 13;
- case Mode.MODE_8BIT_BYTE : return 16;
- case Mode.MODE_KANJI : return 12;
- default :
- throw new Error("mode:" + mode);
- }
-
- } else {
- throw new Error("type:" + type);
- }
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRKanji.as b/src/com/d_project/qrcode/QRKanji.as
deleted file mode 100644
index 4eee788..0000000
--- a/src/com/d_project/qrcode/QRKanji.as
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.d_project.qrcode {
-
- import flash.utils.ByteArray;
-
- /**
- * QRKanji
- * @author Kazuhiko Arase
- */
- internal class QRKanji extends QRData {
-
- public function QRKanji(data : String) {
- super(Mode.MODE_KANJI, data);
- }
-
- public override function write(buffer : BitBuffer) : void {
-
- var data : ByteArray = StringUtil.getBytes(getData(), QRUtil.getJISEncoding() );
-
- var i : int = 0;
-
- while (i + 1 < data.length) {
-
- var c : int = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);
-
- if (0x8140 <= c && c <= 0x9FFC) {
- c -= 0x8140;
- } else if (0xE040 <= c && c <= 0xEBBF) {
- c -= 0xC140;
- } else {
- throw new Error("illegal char at " + (i + 1) + "/" + c);
- }
-
- c = ( (c >>> 8) & 0xff) * 0xC0 + (c & 0xff);
-
- buffer.put(c, 13);
-
- i += 2;
- }
-
- if (i < data.length) {
- throw new Error("illegal char at " + (i + 1) );
- }
- }
-
- public override function getLength() : int {
- return Math.floor(StringUtil.getBytes(getData(), QRUtil.getJISEncoding() ).length / 2);
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRMath.as b/src/com/d_project/qrcode/QRMath.as
deleted file mode 100644
index a5c52e8..0000000
--- a/src/com/d_project/qrcode/QRMath.as
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * QRMath
- * @author Kazuhiko Arase
- */
- internal class QRMath {
-
- function QRMath() {
- throw new Error("");
- }
-
- private static var EXP_TABLE : Array;
- private static var LOG_TABLE : Array;
-
- private static var classInitialized : Boolean = initializeClass();
-
- private static function initializeClass() : Boolean {
-
- var i : int;
-
- EXP_TABLE = new Array(256);
-
- for (i = 0; i < 8; i++) {
- EXP_TABLE[i] = 1 << i;
- }
-
- for (i = 8; i < 256; i++) {
- EXP_TABLE[i] = EXP_TABLE[i - 4]
- ^ EXP_TABLE[i - 5]
- ^ EXP_TABLE[i - 6]
- ^ EXP_TABLE[i - 8];
- }
-
- LOG_TABLE = new Array(256);
- for (i = 0; i < 255; i++) {
- LOG_TABLE[EXP_TABLE[i] ] = i;
- }
-
- return true;
- }
-
- public static function glog(n : int) : int {
-
- if (n < 1) {
- throw new Error("log(" + n + ")");
- }
-
- return LOG_TABLE[n];
- }
-
- public static function gexp(n : int) : int {
-
- while (n < 0) {
- n += 255;
- }
-
- while (n >= 256) {
- n -= 255;
- }
-
- return EXP_TABLE[n];
- }
-
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRNumber.as b/src/com/d_project/qrcode/QRNumber.as
deleted file mode 100644
index 146689d..0000000
--- a/src/com/d_project/qrcode/QRNumber.as
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * QRNumber
- * @author Kazuhiko Arase
- */
- internal class QRNumber extends QRData {
-
- public function QRNumber(data : String) {
- super(Mode.MODE_NUMBER, data);
- }
-
- public override function write(buffer : BitBuffer) : void {
-
- var data : String = getData();
-
- var i : int = 0;
- var num : int;
-
- while (i + 2 < data.length) {
- num = parseInt(data.substring(i, i + 3) );
- buffer.put(num, 10);
- i += 3;
- }
-
- if (i < data.length) {
-
- if (data.length - i == 1) {
- num = parseInt(data.substring(i, i + 1) );
- buffer.put(num, 4);
- } else if (data.length - i == 2) {
- num = parseInt(data.substring(i, i + 2) );
- buffer.put(num, 7);
- }
-
- }
- }
-
- public override function getLength() : int {
- return getData().length;
- }
-
- private static function parseInt(s : String) : int {
- var num : int = 0;
- for (var i : int = 0; i < s.length; i++) {
- num = num * 10 + parseCharCode(s.charCodeAt(i) );
- }
- return num;
- }
-
- private static function parseCharCode(c : int) : int {
-
- if (getCharCode('0') <= c && c <= getCharCode('9') ) {
- return c - getCharCode('0') ;
- }
-
- throw new Error("illegal char :" + c);
- }
-
- private static function getCharCode(c : String) : int {
- return c.charCodeAt(0);
- }
-
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRUtil.as b/src/com/d_project/qrcode/QRUtil.as
deleted file mode 100644
index bd05994..0000000
--- a/src/com/d_project/qrcode/QRUtil.as
+++ /dev/null
@@ -1,345 +0,0 @@
-package com.d_project.qrcode {
-
- import flash.utils.ByteArray;
-
- /**
- * QRUtil
- * @author Kazuhiko Arase
- */
- public class QRUtil {
-
- public static function getJISEncoding() : String {
- return "shift_jis";
- }
-
- public static function getPatternPosition(typeNumber : int) : Array {
- return PATTERN_POSITION_TABLE[typeNumber - 1];
- }
-
- private static var PATTERN_POSITION_TABLE : Array =[
- [],
- [6, 18],
- [6, 22],
- [6, 26],
- [6, 30],
- [6, 34],
- [6, 22, 38],
- [6, 24, 42],
- [6, 26, 46],
- [6, 28, 50],
- [6, 30, 54],
- [6, 32, 58],
- [6, 34, 62],
- [6, 26, 46, 66],
- [6, 26, 48, 70],
- [6, 26, 50, 74],
- [6, 30, 54, 78],
- [6, 30, 56, 82],
- [6, 30, 58, 86],
- [6, 34, 62, 90],
- [6, 28, 50, 72, 94],
- [6, 26, 50, 74, 98],
- [6, 30, 54, 78, 102],
- [6, 28, 54, 80, 106],
- [6, 32, 58, 84, 110],
- [6, 30, 58, 86, 114],
- [6, 34, 62, 90, 118],
- [6, 26, 50, 74, 98, 122],
- [6, 30, 54, 78, 102, 126],
- [6, 26, 52, 78, 104, 130],
- [6, 30, 56, 82, 108, 134],
- [6, 34, 60, 86, 112, 138],
- [6, 30, 58, 86, 114, 142],
- [6, 34, 62, 90, 118, 146],
- [6, 30, 54, 78, 102, 126, 150],
- [6, 24, 50, 76, 102, 128, 154],
- [6, 28, 54, 80, 106, 132, 158],
- [6, 32, 58, 84, 110, 136, 162],
- [6, 26, 54, 82, 110, 138, 166],
- [6, 30, 58, 86, 114, 142, 170]
- ];
-
- private static var MAX_LENGTH : Array = [
- [ [41, 25, 17, 10], [34, 20, 14, 8], [27, 16, 11, 7], [17, 10, 7, 4] ],
- [ [77, 47, 32, 20], [63, 38, 26, 16], [48, 29, 20, 12], [34, 20, 14, 8] ],
- [ [127, 77, 53, 32], [101, 61, 42, 26], [77, 47, 32, 20], [58, 35, 24, 15] ],
- [ [187, 114, 78, 48], [149, 90, 62, 38], [111, 67, 46, 28], [82, 50, 34, 21] ],
- [ [255, 154, 106, 65], [202, 122, 84, 52], [144, 87, 60, 37], [106, 64, 44, 27] ],
- [ [322, 195, 134, 82], [255, 154, 106, 65], [178, 108, 74, 45], [139, 84, 58, 36] ],
- [ [370, 224, 154, 95], [293, 178, 122, 75], [207, 125, 86, 53], [154, 93, 64, 39] ],
- [ [461, 279, 192, 118], [365, 221, 152, 93], [259, 157, 108, 66], [202, 122, 84, 52] ],
- [ [552, 335, 230, 141], [432, 262, 180, 111], [312, 189, 130, 80], [235, 143, 98, 60] ],
- [ [652, 395, 271, 167], [513, 311, 213, 131], [364, 221, 151, 93], [288, 174, 119, 74] ]
- ];
-
- public static function getMaxLength(typeNumber : int, mode : int, errorCorrectLevel : int) : int {
-
- var t : int = typeNumber - 1;
- var e : int = 0;
- var m : int = 0;
-
- switch(errorCorrectLevel) {
- case ErrorCorrectLevel.L : e = 0; break;
- case ErrorCorrectLevel.M : e = 1; break;
- case ErrorCorrectLevel.Q : e = 2; break;
- case ErrorCorrectLevel.H : e = 3; break;
- default :
- throw new Error("e:" + errorCorrectLevel);
- }
-
- switch(mode) {
- case Mode.MODE_NUMBER : m = 0; break;
- case Mode.MODE_ALPHA_NUM : m = 1; break;
- case Mode.MODE_8BIT_BYTE : m = 2; break;
- case Mode.MODE_KANJI : m = 3; break;
- default :
- throw new Error("m:" + mode);
- }
-
- return MAX_LENGTH[t][e][m];
- }
-
-
- /**
- * ã¨ã©ã¼è¨æ£å¤é
å¼ãåå¾ããã
- */
- public static function getErrorCorrectPolynomial(errorCorrectLength : int) : Polynomial{
-
- var a : Polynomial = new Polynomial([1]);
-
- for (var i : int = 0; i < errorCorrectLength; i++) {
- a = a.multiply(new Polynomial([1, QRMath.gexp(i)]) );
- }
-
- return a;
- }
-
- /**
- * æå®ããããã¿ã¼ã³ã®ãã¹ã¯ãåå¾ããã
- */
- public static function getMask(maskPattern : int, i : int, j : int) : Boolean {
-
- switch (maskPattern) {
-
- case MaskPattern.PATTERN000 : return (i + j) % 2 == 0;
- case MaskPattern.PATTERN001 : return i % 2 == 0;
- case MaskPattern.PATTERN010 : return j % 3 == 0;
- case MaskPattern.PATTERN011 : return (i + j) % 3 == 0;
- case MaskPattern.PATTERN100 : return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0;
- case MaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0;
- case MaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0;
- case MaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0;
-
- default :
- throw new Error("mask:" + maskPattern);
- }
- }
-
- /**
- * 失ç¹ãåå¾ãã
- */
- public static function getLostPoint(qrCode : QRCode) : int {
-
- var moduleCount : int = qrCode.getModuleCount();
-
- var lostPoint : int = 0;
-
- var row : int;
- var col : int;
-
- // LEVEL1
-
- for (row = 0; row < moduleCount; row++) {
-
- for (col = 0; col < moduleCount; col++) {
-
- var sameCount : int = 0;
- var dark : Boolean = qrCode.isDark(row, col);
-
- for (var r : int = -1; r <= 1; r++) {
-
- if (row + r < 0 || moduleCount <= row + r) {
- continue;
- }
-
- for (var c : int = -1; c <= 1; c++) {
-
- if (col + c < 0 || moduleCount <= col + c) {
- continue;
- }
-
- if (r == 0 && c == 0) {
- continue;
- }
-
- if (dark == qrCode.isDark(row + r, col + c) ) {
- sameCount++;
- }
- }
- }
-
- if (sameCount > 5) {
- lostPoint += (3 + sameCount - 5);
- }
- }
- }
-
- // LEVEL2
-
- for (row = 0; row < moduleCount - 1; row++) {
- for (col = 0; col < moduleCount - 1; col++) {
- var count : int = 0;
- if (qrCode.isDark(row, col ) ) count++;
- if (qrCode.isDark(row + 1, col ) ) count++;
- if (qrCode.isDark(row, col + 1) ) count++;
- if (qrCode.isDark(row + 1, col + 1) ) count++;
- if (count == 0 || count == 4) {
- lostPoint += 3;
- }
- }
- }
-
- // LEVEL3
-
- for (row = 0; row < moduleCount; row++) {
- for (col = 0; col < moduleCount - 6; col++) {
- if (qrCode.isDark(row, col)
- && !qrCode.isDark(row, col + 1)
- && qrCode.isDark(row, col + 2)
- && qrCode.isDark(row, col + 3)
- && qrCode.isDark(row, col + 4)
- && !qrCode.isDark(row, col + 5)
- && qrCode.isDark(row, col + 6) ) {
- lostPoint += 40;
- }
- }
- }
-
- for (col = 0; col < moduleCount; col++) {
- for (row = 0; row < moduleCount - 6; row++) {
- if (qrCode.isDark(row, col)
- && !qrCode.isDark(row + 1, col)
- && qrCode.isDark(row + 2, col)
- && qrCode.isDark(row + 3, col)
- && qrCode.isDark(row + 4, col)
- && !qrCode.isDark(row + 5, col)
- && qrCode.isDark(row + 6, col) ) {
- lostPoint += 40;
- }
- }
- }
-
- // LEVEL4
-
- var darkCount : int = 0;
-
- for (col = 0; col < moduleCount; col++) {
- for (row = 0; row < moduleCount; row++) {
- if (qrCode.isDark(row, col) ) {
- darkCount++;
- }
- }
- }
-
- var ratio : int = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
- lostPoint += ratio * 10;
-
- return lostPoint;
- }
-
- public static function getMode(s : String) : int {
- if (isAlphaNum(s) ) {
- if (isNumber(s) ) {
- return Mode.MODE_NUMBER;
- }
- return Mode.MODE_ALPHA_NUM;
- } else if (isKanji(s) ) {
- return Mode.MODE_KANJI;
- } else {
- return Mode.MODE_8BIT_BYTE;
- }
- }
-
- private static function isNumber(s : String) : Boolean {
- for (var i : int = 0; i < s.length; i++) {
- var c : String = s.charAt(i);
- if (!('0' <= c && c <= '9') ) {
- return false;
- }
- }
- return true;
- }
-
- private static function isAlphaNum(s : String) : Boolean {
- for (var i : int = 0; i < s.length; i++) {
- var c : String = s.charAt(i);
- if (!('0' <= c && c <= '9') && !('A' <= c && c <= 'Z') && " $%*+-./:".indexOf(c) == -1) {
- return false;
- }
- }
- return true;
- }
-
- private static function isKanji(s : String) : Boolean {
-
- var data : ByteArray = StringUtil.getBytes(s, QRUtil.getJISEncoding() );
-
- var i : int = 0;
-
- while (i + 1 < data.length) {
-
- var c : int = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);
-
- if (!(0x8140 <= c && c <= 0x9FFC) && !(0xE040 <= c && c <= 0xEBBF) ) {
- return false;
- }
-
- i += 2;
- }
-
- if (i < data.length) {
- return false;
- }
-
- return true;
- }
-
- private static const G15 : int = (1 << 10) | (1 << 8) | (1 << 5)
- | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
-
- private static const G18 : int = (1 << 12) | (1 << 11) | (1 << 10)
- | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
-
- private static const G15_MASK : int = (1 << 14) | (1 << 12) | (1 << 10)
- | (1 << 4) | (1 << 1);
-
- public static function getBCHTypeInfo(data : int) : int {
- var d : int = data << 10;
- while (getBCHDigit(d) - getBCHDigit(G15) >= 0) {
- d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15) ) );
- }
- return ( (data << 10) | d) ^ G15_MASK;
- }
-
- public static function getBCHTypeNumber(data : int) : int {
- var d : int = data << 12;
- while (getBCHDigit(d) - getBCHDigit(G18) >= 0) {
- d ^= (G18 << (getBCHDigit(d) - getBCHDigit(G18) ) );
- }
- return (data << 12) | d;
- }
-
- private static function getBCHDigit(data : int) : int {
-
- var digit : int = 0;
-
- while (data != 0) {
- digit++;
- data >>>= 1;
- }
-
- return digit;
-
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/RSBlock.as b/src/com/d_project/qrcode/RSBlock.as
deleted file mode 100644
index c53c5be..0000000
--- a/src/com/d_project/qrcode/RSBlock.as
+++ /dev/null
@@ -1,139 +0,0 @@
-package com.d_project.qrcode {
-
- /**
- * RSBlock
- * @author Kazuhiko Arase
- */
- internal class RSBlock {
-
- private static var RS_BLOCK_TABLE : Array = [
-
- // L
- // M
- // Q
- // H
-
- // 1
- [1, 26, 19],
- [1, 26, 16],
- [1, 26, 13],
- [1, 26, 9],
-
- // 2
- [1, 44, 34],
- [1, 44, 28],
- [1, 44, 22],
- [1, 44, 16],
-
- // 3
- [1, 70, 55],
- [1, 70, 44],
- [2, 35, 17],
- [2, 35, 13],
-
- // 4
- [1, 100, 80],
- [2, 50, 32],
- [2, 50, 24],
- [4, 25, 9],
-
- // 5
- [1, 134, 108],
- [2, 67, 43],
- [2, 33, 15, 2, 34, 16],
- [2, 33, 11, 2, 34, 12],
-
- // 6
- [2, 86, 68],
- [4, 43, 27],
- [4, 43, 19],
- [4, 43, 15],
-
- // 7
- [2, 98, 78],
- [4, 49, 31],
- [2, 32, 14, 4, 33, 15],
- [4, 39, 13, 1, 40, 14],
-
- // 8
- [2, 121, 97],
- [2, 60, 38, 2, 61, 39],
- [4, 40, 18, 2, 41, 19],
- [4, 40, 14, 2, 41, 15],
-
- // 9
- [2, 146, 116],
- [3, 58, 36, 2, 59, 37],
- [4, 36, 16, 4, 37, 17],
- [4, 36, 12, 4, 37, 13],
-
- // 10
- [2, 86, 68, 2, 87, 69],
- [4, 69, 43, 1, 70, 44],
- [6, 43, 19, 2, 44, 20],
- [6, 43, 15, 2, 44, 16]
-
- ];
-
- private var totalCount : int;
- private var dataCount : int;
-
- public function RSBlock(totalCount : int, dataCount : int) {
- this.totalCount = totalCount;
- this.dataCount = dataCount;
- }
-
- public function getDataCount() : int {
- return dataCount;
- }
-
- public function getTotalCount() : int {
- return totalCount;
- }
-
- public static function getRSBlocks(typeNumber : int, errorCorrectLevel : int) : Array {
-
- var rsBlock : Array = getRsBlockTable(typeNumber, errorCorrectLevel);
- var length : int = Math.floor(rsBlock.length / 3);
- var list : Array = new Array();
-
- for (var i : int = 0; i < length; i++) {
-
- var count : int = rsBlock[i * 3 + 0];
- var totalCount : int = rsBlock[i * 3 + 1];
- var dataCount : int = rsBlock[i * 3 + 2];
-
- for (var j : int = 0; j < count; j++) {
- list.push(new RSBlock(totalCount, dataCount) );
- }
- }
-
- return list;
- }
-
- private static function getRsBlockTable(typeNumber : int, errorCorrectLevel : int) : Array {
-
- try {
-
- switch(errorCorrectLevel) {
- case ErrorCorrectLevel.L :
- return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
- case ErrorCorrectLevel.M :
- return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
- case ErrorCorrectLevel.Q :
- return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
- case ErrorCorrectLevel.H :
- return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
- default :
- break;
- }
-
- } catch(e : Error) {
- }
-
- throw new Error("tn:" + typeNumber + "/ecl:" + errorCorrectLevel);
- }
-
- }
-
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/StringUtil.as b/src/com/d_project/qrcode/StringUtil.as
deleted file mode 100644
index ae94888..0000000
--- a/src/com/d_project/qrcode/StringUtil.as
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.d_project.qrcode {
-
- import flash.utils.ByteArray;
-
- /**
- * StringUtil
- * @author Kazuhiko Arase
- */
- internal class StringUtil {
-
- public static function getBytes(s : String, encoding : String) : ByteArray {
- var b : ByteArray = new ByteArray();
- b.writeMultiByte(s, encoding);
- return b;
- }
- }
-}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/mx/QRCode.as b/src/com/d_project/qrcode/mx/QRCode.as
deleted file mode 100644
index ba74e14..0000000
--- a/src/com/d_project/qrcode/mx/QRCode.as
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.d_project.qrcode.mx {
-
- import mx.core.UIComponent;
- import flash.display.Graphics;
-
- import com.d_project.qrcode.ErrorCorrectLevel;
-
-
- /**
- * QRCode
- * @author Kazuhiko Arase
- */
- public class QRCode extends UIComponent {
-
- private var qr : com.d_project.qrcode.QRCode;
-
- private var _text : String;
-
- [Inspectable(enumeration="L,M,Q,H", defaultValue="H")]
- public var errorCorrectLevel : String = "H";
-
- public function QRCode() {
- _text = "QRCode";
- qr = null;
- }
-
- public function get text() : String {
- return _text;
- }
-
- public function set text(value : String) : void {
- _text = value;
- qr = null;
- invalidateDisplayList();
- }
-
- protected override function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void {
-
- var padding : Number = 10;
-
- var size : Number = Math.min(unscaledWidth, unscaledHeight) - padding * 2;
- var xOffset : Number = (unscaledWidth - size) / 2;
- var yOffset : Number = (unscaledHeight - size) / 2;
-
- if (qr == null) {
- qr = com.d_project.qrcode.QRCode.getMinimumQRCode(text, ErrorCorrectLevel[errorCorrectLevel]);
- }
-
- var cs : Number = size / qr.getModuleCount();
-
- var g : Graphics = graphics;
-
- g.beginFill(0xffffff);
- g.drawRect(0, 0, unscaledWidth, unscaledHeight);
- g.endFill();
-
- for (var row : int = 0; row < qr.getModuleCount(); row++) {
- for (var col : int = 0; col < qr.getModuleCount(); col++) {
- g.beginFill( (qr.isDark(row, col)? 0 : 0xffffff) );
- g.drawRect(cs * col + xOffset, cs * row + yOffset, cs, cs);
- g.endFill();
- }
- }
- }
- }
-}
-
diff --git a/src/com/rails2u/utils/ColorUtil.as b/src/com/rails2u/utils/ColorUtil.as
index 3582ea3..91ac765 100644
--- a/src/com/rails2u/utils/ColorUtil.as
+++ b/src/com/rails2u/utils/ColorUtil.as
@@ -1,36 +1,56 @@
package com.rails2u.utils
{
public class ColorUtil
{
public static function random(
rMin:uint = 0,
gMin:uint = 0,
bMin:uint = 0,
rMax:uint = 255,
gMax:uint = 255,
bMax:uint = 255
):uint
{
return (uint(Math.random() * (rMax - rMin)) + rMin) << 16 |
(uint(Math.random() * (gMax - gMin)) + gMin) << 8 |
(uint(Math.random() * (bMax - bMin)) + bMin);
}
public static function random32(
rMin:uint = 0,
gMin:uint = 0,
bMin:uint = 0,
aMin:uint = 0,
rMax:uint = 255,
gMax:uint = 255,
bMax:uint = 255,
aMax:uint = 255
):uint
{
return (uint(Math.random() * (aMax - aMin)) + aMin) << 24 |
(uint(Math.random() * (rMax - rMin)) + rMin) << 16 |
(uint(Math.random() * (gMax - gMin)) + gMin) << 8 |
(uint(Math.random() * (bMax - bMin)) + bMin);
}
+
+ public static function sinArray(start:int = 255, end:int = 0, cycle:uint = 90):Array {
+ var f:Function = sinGenerator(start, end, cycle);
+ var a:Array = [];
+ for (var i:uint = 0; i < cycle; i++) {
+ // a.push(f(
+ }
+ }
+
+ public static function sinGenerator(start:int = 255, end:int = 0, cycle:uint = 90):Function {
+ var times:uint = 0;
+ var diff:int = start - end;
+ var p:Number;
+ return function():uint {
+ p = (Math.sin(Math.PI/2 + Math.PI * 2 * (360 / cycle * times) / 360) + 1) / 2;
+ times++;
+ if(times >= cycle) times = 0;
+ return end + (diff * p);
+ }
+ }
}
-}
\ No newline at end of file
+}
|
hotchpotch/as3rails2u
|
d4c2dd1fdfe065e9f774f1b020cc0d94572ea93c
|
QRã³ã¼ããçæãã
|
diff --git a/src/com/d_project/qrcode/BitBuffer.as b/src/com/d_project/qrcode/BitBuffer.as
new file mode 100644
index 0000000..7ed3114
--- /dev/null
+++ b/src/com/d_project/qrcode/BitBuffer.as
@@ -0,0 +1,59 @@
+package com.d_project.qrcode {
+
+ /**
+ * BitBuffer
+ * @author Kazuhiko Arase
+ */
+ internal class BitBuffer {
+
+ private var buffer : Array;
+
+ private var length : int;
+
+ public function BitBuffer() {
+ buffer = new Array();
+ length = 0;
+ }
+
+ public function getBuffer() : Array {
+ return buffer;
+ }
+
+ public function getLengthInBits() : int {
+ return length;
+ }
+
+ private function getBitAt(index : int) : Boolean {
+ return ( (buffer[Math.floor(index / 8)] >>> (7 - index % 8) ) & 1) == 1;
+ }
+
+ public function put(num : int, length : int) : void {
+ for (var i : int = 0; i < length; i++) {
+ putBit( ( (num >>> (length - i - 1) ) & 1) == 1);
+ }
+ }
+
+ public function putBit(bit : Boolean) : void {
+
+ if (length == buffer.length * 8) {
+ buffer.push(0);
+ }
+
+ if (bit) {
+ buffer[Math.floor(length / 8)] |= (0x80 >>> (length % 8) );
+ }
+
+ length++;
+ }
+
+ public function toString() : String {
+ var buffer : String = "";
+ for (var i : int = 0; i < getLengthInBits(); i++) {
+ buffer += (getBitAt(i)? '1' : '0');
+ }
+ return buffer;
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/ErrorCorrectLevel.as b/src/com/d_project/qrcode/ErrorCorrectLevel.as
new file mode 100644
index 0000000..7061604
--- /dev/null
+++ b/src/com/d_project/qrcode/ErrorCorrectLevel.as
@@ -0,0 +1,31 @@
+package com.d_project.qrcode {
+
+ /**
+ * 誤ãè¨æ£ã¬ãã«.
+ * @author Kazuhiko Arase
+ */
+ public class ErrorCorrectLevel {
+
+ /**
+ * 復å
è½å 7%.
+ * <br>vodafoneã§ä½¿ç¨ä¸å¯?
+ */
+ public static const L : int = 1;
+
+ /**
+ * 復å
è½å 15%.
+ */
+ public static const M : int = 0;
+
+ /**
+ * 復å
è½å 25%.
+ */
+ public static const Q : int = 3;
+
+ /**
+ * 復å
è½å 30%.
+ */
+ public static const H : int = 2;
+
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/MaskPattern.as b/src/com/d_project/qrcode/MaskPattern.as
new file mode 100644
index 0000000..2d177c9
--- /dev/null
+++ b/src/com/d_project/qrcode/MaskPattern.as
@@ -0,0 +1,52 @@
+package com.d_project.qrcode {
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³.
+ * @author Kazuhiko Arase
+ */
+ internal class MaskPattern {
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³000
+ */
+ public static const PATTERN000 : int = 0;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³001
+ */
+ public static const PATTERN001 : int = 1;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³010
+ */
+ public static const PATTERN010 : int = 2;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³011
+ */
+ public static const PATTERN011 : int = 3;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³100
+ */
+ public static const PATTERN100 : int = 4;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³101
+ */
+ public static const PATTERN101 : int = 5;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³110
+ */
+ public static const PATTERN110 : int = 6;
+
+ /**
+ * ãã¹ã¯ãã¿ã¼ã³111
+ */
+ public static const PATTERN111 : int = 7;
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/Mode.as b/src/com/d_project/qrcode/Mode.as
new file mode 100644
index 0000000..9a36633
--- /dev/null
+++ b/src/com/d_project/qrcode/Mode.as
@@ -0,0 +1,35 @@
+package com.d_project.qrcode {
+
+ /**
+ * ã¢ã¼ã.
+ * @author Kazuhiko Arase
+ */
+ public class Mode {
+
+ /**
+ * èªåã¢ã¼ã
+ */
+ public static const MODE_AUTO : int = 0;
+
+ /**
+ * æ°å¤ã¢ã¼ã
+ */
+ public static const MODE_NUMBER : int = 1 << 0;
+
+ /**
+ * è±æ°åã¢ã¼ã
+ */
+ public static const MODE_ALPHA_NUM : int = 1 << 1;
+
+ /**
+ * 8ããããã¤ãã¢ã¼ã
+ */
+ public static const MODE_8BIT_BYTE : int = 1 << 2;
+
+ /**
+ * æ¼¢åã¢ã¼ã
+ */
+ public static const MODE_KANJI : int = 1 << 3;
+
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/Polynomial.as b/src/com/d_project/qrcode/Polynomial.as
new file mode 100644
index 0000000..e9191bf
--- /dev/null
+++ b/src/com/d_project/qrcode/Polynomial.as
@@ -0,0 +1,103 @@
+package com.d_project.qrcode {
+
+ /**
+ * Polynomial
+ * @author Kazuhiko Arase
+ */
+ internal class Polynomial {
+
+ private var num : Array;
+
+ public function Polynomial(num : Array, shift : int = 0) {
+
+ var offset : int = 0;
+
+ while (offset < num.length && num[offset] == 0) {
+ offset++;
+ }
+
+ this.num = new Array(num.length - offset + shift);
+ for (var i : int = 0; i < num.length - offset; i++) {
+ this.num[i] = num[offset + i];
+ }
+ }
+
+ public function getAt(index : int) : int {
+ return num[index];
+ }
+
+ public function getLength() : int {
+ return num.length;
+ }
+
+ public function toString() : String {
+
+ var buffer : String = "";
+
+ for (var i : int = 0; i < getLength(); i++) {
+ if (i > 0) {
+ buffer += ",";
+ }
+ buffer += getAt(i);
+ }
+
+ return buffer;
+ }
+
+ public function toLogString() : String {
+
+ var buffer : String = "";
+
+ for (var i : int = 0; i < getLength(); i++) {
+ if (i > 0) {
+ buffer += ",";
+ }
+ buffer += QRMath.glog(getAt(i) );
+
+ }
+
+ return buffer.toString();
+ }
+
+ public function multiply(e : Polynomial) : Polynomial {
+
+ var num : Array = new Array(getLength() + e.getLength() - 1);
+
+ for (var i : int = 0; i < getLength(); i++) {
+ for (var j : int = 0; j < e.getLength(); j++) {
+ num[i + j] ^= QRMath.gexp(QRMath.glog(getAt(i) ) + QRMath.glog(e.getAt(j) ) );
+ }
+ }
+
+ return new Polynomial(num);
+ }
+
+ public function mod(e : Polynomial) : Polynomial {
+
+ if (getLength() - e.getLength() < 0) {
+ return this;
+ }
+
+ // æä¸ä½æ¡ã®æ¯ç
+ var ratio : int = QRMath.glog(getAt(0) ) - QRMath.glog(e.getAt(0) );
+
+ var i : int;
+
+ // ã³ãã¼ä½æ
+ var num : Array = new Array(getLength() );
+ for (i = 0; i < getLength(); i++) {
+ num[i] = getAt(i);
+ }
+
+ // å¼ãç®ãã¦ä½ããè¨ç®
+ for (i = 0; i < e.getLength(); i++) {
+ num[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i) ) + ratio);
+ }
+
+ // å帰è¨ç®
+ return new Polynomial(num).mod(e);
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QR8BitByte.as b/src/com/d_project/qrcode/QR8BitByte.as
new file mode 100644
index 0000000..02b019e
--- /dev/null
+++ b/src/com/d_project/qrcode/QR8BitByte.as
@@ -0,0 +1,26 @@
+package com.d_project.qrcode {
+
+ import flash.utils.ByteArray;
+
+ /**
+ * QR8BitByte
+ * @author Kazuhiko Arase
+ */
+ internal class QR8BitByte extends QRData {
+
+ public function QR8BitByte(data : String) {
+ super(Mode.MODE_8BIT_BYTE, data);
+ }
+
+ public override function write(buffer : BitBuffer) : void {
+ var data : ByteArray = StringUtil.getBytes(getData(), QRUtil.getJISEncoding() );
+ for (var i : int = 0; i < data.length; i++) {
+ buffer.put(data[i], 8);
+ }
+ }
+
+ public override function getLength() : int {
+ return StringUtil.getBytes(getData(), QRUtil.getJISEncoding() ).length;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRAlphaNum.as b/src/com/d_project/qrcode/QRAlphaNum.as
new file mode 100644
index 0000000..cd4e86b
--- /dev/null
+++ b/src/com/d_project/qrcode/QRAlphaNum.as
@@ -0,0 +1,60 @@
+package com.d_project.qrcode {
+
+ /**
+ * QRAlphaNum
+ * @author Kazuhiko Arase
+ */
+ internal class QRAlphaNum extends QRData {
+
+ public function QRAlphaNum(data : String) {
+ super(Mode.MODE_ALPHA_NUM, data);
+ }
+
+ public override function write(buffer : BitBuffer) : void {
+
+ var i : int = 0;
+ var s : String = getData();
+
+ while (i + 1 < s.length) {
+ buffer.put(getCode(s.charAt(i) ) * 45 + getCode(s.charAt(i + 1) ), 11);
+ i += 2;
+ }
+
+ if (i < s.length) {
+ buffer.put(getCode(s.charAt(i) ), 6);
+ }
+ }
+
+ public override function getLength() : int {
+ return getData().length;
+ }
+
+ private static function getCode(c : String) : int {
+ var code : int = c.charCodeAt(0);
+ if (getCharCode('0') <= code && code <= getCharCode('9') ) {
+ return code - getCharCode('0');
+ } else if (getCharCode('A') <= code && code <= getCharCode('Z') ) {
+ return code - getCharCode('A') + 10;
+ } else {
+ switch (c) {
+ case ' ' : return 36;
+ case '$' : return 37;
+ case '%' : return 38;
+ case '*' : return 39;
+ case '+' : return 40;
+ case '-' : return 41;
+ case '.' : return 42;
+ case '/' : return 43;
+ case ':' : return 44;
+ default :
+ throw new Error("illegal char :" + c);
+ }
+ }
+ throw new Error();
+ }
+
+ private static function getCharCode(c : String) : int {
+ return c.charCodeAt(0);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRCode.as b/src/com/d_project/qrcode/QRCode.as
new file mode 100644
index 0000000..a72e5d1
--- /dev/null
+++ b/src/com/d_project/qrcode/QRCode.as
@@ -0,0 +1,550 @@
+package com.d_project.qrcode {
+
+ /**
+ * QRã³ã¼ã.
+ * <br/>
+ * â ä½¿ãæ¹
+ * <ul>
+ * <li>誤ãè¨æ£ã¬ãã«ããã¼ã¿çã諸ãã©ã¡ã¼ã¿ãè¨å®ãã¾ãã</li>
+ * <li>make() ãå¼ã³åºãã¦QRã³ã¼ãã使ãã¾ãã</li>
+ * <li>getModuleCount() 㨠isDark() ã§ãQRã³ã¼ãã®ãã¼ã¿ãåå¾ãã¾ãã</li>
+ * </ul>
+ * @author Kazuhiko Arase
+ */
+ public class QRCode {
+
+ private static const PAD0 : int = 0xEC;
+
+ private static const PAD1 : int = 0x11;
+
+ private var typeNumber : int;
+
+ private var modules : Array;
+
+ private var moduleCount : int;
+
+ private var errorCorrectLevel : int;
+
+ private var qrDataList : Array;
+
+ /**
+ * ã³ã³ã¹ãã©ã¯ã¿
+ * <br>åçª1, 誤ãè¨æ£ã¬ãã«H ã®QRã³ã¼ãã®ã¤ã³ã¹ã¿ã³ã¹ãçæãã¾ãã
+ * @see ErrorCorrectLevel
+ */
+ public function QRCode() {
+ this.typeNumber = 1;
+ this.errorCorrectLevel = ErrorCorrectLevel.H;
+ this.qrDataList = new Array();
+ }
+
+ /**
+ * åçªãåå¾ããã
+ * @return åçª
+ */
+ public function getTypeNumber() : int {
+ return typeNumber;
+ }
+
+ /**
+ * åçªãè¨å®ããã
+ * @param typeNumber åçª
+ */
+ public function setTypeNumber(typeNumber : int) : void {
+ this.typeNumber = typeNumber;
+ }
+
+ /**
+ * 誤ãè¨æ£ã¬ãã«ãåå¾ããã
+ * @return 誤ãè¨æ£ã¬ãã«
+ * @see ErrorCorrectLevel
+ */
+ public function getErrorCorrectLevel() : int {
+ return errorCorrectLevel;
+ }
+
+ /**
+ * 誤ãè¨æ£ã¬ãã«ãè¨å®ããã
+ * @param errorCorrectLevel 誤ãè¨æ£ã¬ãã«
+ * @see ErrorCorrectLevel
+ */
+ public function setErrorCorrectLevel(errorCorrectLevel : int) : void {
+ this.errorCorrectLevel = errorCorrectLevel;
+ }
+
+ /**
+ * ã¢ã¼ããæå®ãã¦ãã¼ã¿ã追å ããã
+ * @param data ãã¼ã¿
+ * @param mode ã¢ã¼ã
+ * @see Mode
+ */
+ public function addData(data : String, mode : int = 0) : void {
+
+ if (mode == Mode.MODE_AUTO) {
+ mode = QRUtil.getMode(data);
+ }
+
+ switch(mode) {
+
+ case Mode.MODE_NUMBER :
+ addQRData(new QRNumber(data) );
+ break;
+
+ case Mode.MODE_ALPHA_NUM :
+ addQRData(new QRAlphaNum(data) );
+ break;
+
+ case Mode.MODE_8BIT_BYTE :
+ addQRData(new QR8BitByte(data) );
+ break;
+
+ case Mode.MODE_KANJI :
+ addQRData(new QRKanji(data) );
+ break;
+
+ default :
+ throw new Error("mode:" + mode);
+ }
+ }
+
+ /**
+ * ãã¼ã¿ãã¯ãªã¢ããã
+ * <br/>addData ã§è¿½å ããããã¼ã¿ãã¯ãªã¢ãã¾ãã
+ */
+ public function clearData() : void {
+ qrDataList = new Array();
+ }
+
+ private function addQRData(qrData : QRData) : void {
+ qrDataList.push(qrData);
+ }
+
+ private function getQRDataCount() : int {
+ return qrDataList.length;
+ }
+
+ private function getQRData(index : int) : QRData {
+ return qrDataList[index];
+ }
+
+ /**
+ * æã¢ã¸ã¥ã¼ã«ãã©ãããåå¾ããã
+ * @param row è¡ (0 ï½ ã¢ã¸ã¥ã¼ã«æ° - 1)
+ * @param col å (0 ï½ ã¢ã¸ã¥ã¼ã«æ° - 1)
+ */
+ public function isDark(row : int, col : int) : Boolean {
+ if (modules[row][col] != null) {
+ return modules[row][col];
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * ã¢ã¸ã¥ã¼ã«æ°ãåå¾ããã
+ */
+ public function getModuleCount() : int {
+ return moduleCount;
+ }
+
+ /**
+ * QRã³ã¼ãã使ããã
+ */
+ public function make() : void {
+ makeImpl(false, getBestMaskPattern() );
+ }
+
+ private function getBestMaskPattern() : int {
+
+ var minLostPoint : int = 0;
+ var pattern : int = 0;
+
+ for (var i : int = 0; i < 8; i++) {
+
+ makeImpl(true, i);
+
+ var lostPoint : int = QRUtil.getLostPoint(this);
+
+ if (i == 0 || minLostPoint > lostPoint) {
+ minLostPoint = lostPoint;
+ pattern = i;
+ }
+ }
+
+ return pattern;
+ }
+
+ /**
+ *
+ */
+ private function makeImpl(test : Boolean, maskPattern : int) : void {
+
+ // ã¢ã¸ã¥ã¼ã«åæå
+ moduleCount = typeNumber * 4 + 17;
+ modules = new Array(moduleCount);
+ for (var i : int = 0; i < moduleCount; i++) {
+ modules[i] = new Array(moduleCount);
+ }
+
+ // ä½ç½®æ¤åºãã¿ã¼ã³åã³åé¢ãã¿ã¼ã³ãè¨å®
+ setupPositionProbePattern(0, 0);
+ setupPositionProbePattern(moduleCount - 7, 0);
+ setupPositionProbePattern(0, moduleCount - 7);
+
+ setupPositionAdjustPattern();
+ setupTimingPattern();
+
+ setupTypeInfo(test, maskPattern);
+
+ if (typeNumber >= 7) {
+ setupTypeNumber(test);
+ }
+
+ var dataArray : Array = qrDataList;
+ var data : Array = createData(typeNumber, errorCorrectLevel, dataArray);
+
+ mapData(data, maskPattern);
+ }
+
+ private function mapData(data : Array, maskPattern : int) : void {
+
+ var inc : int = -1;
+ var row : int = moduleCount - 1;
+ var bitIndex : int = 7;
+ var byteIndex : int = 0;
+
+ for (var col : int = moduleCount - 1; col > 0; col -= 2) {
+
+ if (col == 6) col--;
+
+ while (true) {
+
+ for (var c : int = 0; c < 2; c++) {
+
+ if (modules[row][col - c] == null) {
+
+ var dark : Boolean = false;
+
+ if (byteIndex < data.length) {
+ dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1);
+ }
+
+ var mask : Boolean = QRUtil.getMask(maskPattern, row, col - c);
+
+ if (mask) {
+ dark = !dark;
+ }
+
+ modules[row][col - c] = (dark);
+ bitIndex--;
+
+ if (bitIndex == -1) {
+ byteIndex++;
+ bitIndex = 7;
+ }
+ }
+ }
+
+ row += inc;
+
+ if (row < 0 || moduleCount <= row) {
+ row -= inc;
+ inc = -inc;
+ break;
+ }
+ }
+ }
+
+ }
+
+ /**
+ * ä½ç½®åãããã¿ã¼ã³ãè¨å®
+ */
+ private function setupPositionAdjustPattern() : void {
+
+ var pos : Array = QRUtil.getPatternPosition(typeNumber);
+
+ for (var i : int = 0; i < pos.length; i++) {
+
+ for (var j : int = 0; j < pos.length; j++) {
+
+ var row : int = pos[i];
+ var col : int = pos[j];
+
+ if (modules[row][col] != null) {
+ continue;
+ }
+
+ for (var r : int = -2; r <= 2; r++) {
+
+ for (var c : int = -2; c <= 2; c++) {
+
+ if (r == -2 || r == 2 || c == -2 || c == 2
+ || (r == 0 && c == 0) ) {
+ modules[row + r][col + c] = (true);
+ } else {
+ modules[row + r][col + c] = (false);
+ }
+ }
+ }
+
+ }
+ }
+ }
+
+ /**
+ * ä½ç½®æ¤åºãã¿ã¼ã³ãè¨å®
+ */
+ private function setupPositionProbePattern(row : int, col : int) : void {
+
+ for (var r : int = -1; r <= 7; r++) {
+
+ for (var c : int = -1; c <= 7; c++) {
+
+ if (row + r <= -1 || moduleCount <= row + r
+ || col + c <= -1 || moduleCount <= col + c) {
+ continue;
+ }
+
+ if ( (0 <= r && r <= 6 && (c == 0 || c == 6) )
+ || (0 <= c && c <= 6 && (r == 0 || r == 6) )
+ || (2 <= r && r <= 4 && 2 <= c && c <= 4) ) {
+ modules[row + r][col + c] = (true);
+ } else {
+ modules[row + r][col + c] = (false);
+ }
+ }
+ }
+ }
+
+ /**
+ * ã¿ã¤ãã³ã°ãã¿ã¼ã³ãè¨å®
+ */
+ private function setupTimingPattern() : void {
+ for (var r : int = 8; r < moduleCount - 8; r++) {
+ if (modules[r][6] != null) {
+ continue;
+ }
+ modules[r][6] = (r % 2 == 0);
+ }
+ for (var c : int = 8; c < moduleCount - 8; c++) {
+ if (modules[6][c] != null) {
+ continue;
+ }
+ modules[6][c] = (c % 2 == 0);
+ }
+ }
+
+ /**
+ * åçªãè¨å®
+ */
+ private function setupTypeNumber(test : Boolean) : void {
+
+ var bits : int = QRUtil.getBCHTypeNumber(typeNumber);
+ var i : int;
+ var mod : Boolean;
+
+ for (i = 0; i < 18; i++) {
+ mod = (!test && ( (bits >> i) & 1) == 1);
+ modules[Math.floor(i / 3)][i % 3 + moduleCount - 8 - 3] = mod;
+ }
+
+ for (i = 0; i < 18; i++) {
+ mod = (!test && ( (bits >> i) & 1) == 1);
+ modules[i % 3 + moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
+ }
+ }
+
+ /**
+ * 形弿
å ±ãè¨å®
+ */
+ private function setupTypeInfo(test : Boolean, maskPattern : int) : void {
+
+ var data : int = (errorCorrectLevel << 3) | maskPattern;
+ var bits : int = QRUtil.getBCHTypeInfo(data);
+ var i : int;
+ var mod : Boolean;
+
+ // 縦æ¹å
+ for (i = 0; i < 15; i++) {
+
+ mod = (!test && ( (bits >> i) & 1) == 1);
+
+ if (i < 6) {
+ modules[i][8] = mod;
+ } else if (i < 8) {
+ modules[i + 1][8] = mod;
+ } else {
+ modules[moduleCount - 15 + i][8] = mod;
+ }
+ }
+
+ // 横æ¹å
+ for (i = 0; i < 15; i++) {
+
+ mod = (!test && ( (bits >> i) & 1) == 1);
+
+ if (i < 8) {
+ modules[8][moduleCount - i - 1] = mod;
+ } else if (i < 9) {
+ modules[8][15 - i - 1 + 1] = mod;
+ } else {
+ modules[8][15 - i - 1] = mod;
+ }
+ }
+
+ // åºå®
+ modules[moduleCount - 8][8] = (!test);
+
+ }
+
+ private static function createData(typeNumber : int, errorCorrectLevel : int, dataArray : Array) : Array {
+
+ var rsBlocks : Array = RSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
+ var buffer : BitBuffer = new BitBuffer();
+ var i : int;
+
+ for (i = 0; i < dataArray.length; i++) {
+ var data : QRData = dataArray[i];
+ buffer.put(data.getMode(), 4);
+ buffer.put(data.getLength(), data.getLengthInBits(typeNumber) );
+ data.write(buffer);
+ }
+
+ // æå¤§ãã¼ã¿æ°ãè¨ç®
+ var totalDataCount : int = 0;
+ for (i = 0; i < rsBlocks.length; i++) {
+ totalDataCount += rsBlocks[i].getDataCount();
+ }
+
+ if (buffer.getLengthInBits() > totalDataCount * 8) {
+ throw new Error("code length overflow. ("
+ + buffer.getLengthInBits()
+ + ">"
+ + totalDataCount * 8
+ + ")");
+ }
+
+ // çµç«¯ã³ã¼ã
+ if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
+ buffer.put(0, 4);
+ }
+
+ // padding
+ while (buffer.getLengthInBits() % 8 != 0) {
+ buffer.putBit(false);
+ }
+
+ // padding
+ while (true) {
+
+ if (buffer.getLengthInBits() >= totalDataCount * 8) {
+ break;
+ }
+ buffer.put(PAD0, 8);
+
+ if (buffer.getLengthInBits() >= totalDataCount * 8) {
+ break;
+ }
+ buffer.put(PAD1, 8);
+ }
+
+ return createBytes(buffer, rsBlocks);
+ }
+
+ private static function createBytes(buffer : BitBuffer, rsBlocks : Array) : Array {
+
+ var offset : int = 0;
+
+ var maxDcCount : int = 0;
+ var maxEcCount : int = 0;
+
+ var dcdata : Array = new Array(rsBlocks.length);
+ var ecdata : Array = new Array(rsBlocks.length);
+
+ var i : int;
+ var r : int;
+
+ for (r = 0; r < rsBlocks.length; r++) {
+
+ var dcCount : int = rsBlocks[r].getDataCount();
+ var ecCount : int = rsBlocks[r].getTotalCount() - dcCount;
+
+ maxDcCount = Math.max(maxDcCount, dcCount);
+ maxEcCount = Math.max(maxEcCount, ecCount);
+
+ dcdata[r] = new Array(dcCount);
+ for (i = 0; i < dcdata[r].length; i++) {
+ dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset];
+ }
+ offset += dcCount;
+
+ var rsPoly : Polynomial = QRUtil.getErrorCorrectPolynomial(ecCount);
+ var rawPoly : Polynomial = new Polynomial(dcdata[r], rsPoly.getLength() - 1);
+
+ var modPoly : Polynomial = rawPoly.mod(rsPoly);
+ ecdata[r] = new Array(rsPoly.getLength() - 1);
+ for (i = 0; i < ecdata[r].length; i++) {
+ var modIndex : int = i + modPoly.getLength() - ecdata[r].length;
+ ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0;
+ }
+
+ }
+
+ var totalCodeCount : int = 0;
+ for (i = 0; i < rsBlocks.length; i++) {
+ totalCodeCount += rsBlocks[i].getTotalCount();
+ }
+
+ var data : Array = new Array(totalCodeCount);
+
+ var index : int = 0;
+
+ for (i = 0; i < maxDcCount; i++) {
+ for (r = 0; r < rsBlocks.length; r++) {
+ if (i < dcdata[r].length) {
+ data[index++] = dcdata[r][i];
+ }
+ }
+ }
+
+ for (i = 0; i < maxEcCount; i++) {
+ for (r = 0; r < rsBlocks.length; r++) {
+ if (i < ecdata[r].length) {
+ data[index++] = ecdata[r][i];
+ }
+ }
+ }
+
+ return data;
+
+ }
+
+ /**
+ * æå°ã®åçªã¨ãªã QRCode ã使ããã
+ * @param data ãã¼ã¿
+ * @param errorCorrectLevel 誤ãè¨æ£ã¬ãã«
+ */
+ public static function getMinimumQRCode(data : String, errorCorrectLevel : int) : QRCode {
+
+ var mode : int = QRUtil.getMode(data);
+
+ var qr : QRCode = new QRCode();
+ qr.setErrorCorrectLevel(errorCorrectLevel);
+ qr.addData(data, mode);
+
+ var length : int = qr.getQRData(0).getLength();
+
+ for (var typeNumber : int = 1; typeNumber <= 10; typeNumber++) {
+ if (length <= QRUtil.getMaxLength(typeNumber, mode, errorCorrectLevel) ) {
+ qr.setTypeNumber(typeNumber);
+ break;
+ }
+ }
+
+ qr.make();
+
+ return qr;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRData.as b/src/com/d_project/qrcode/QRData.as
new file mode 100644
index 0000000..88f34bf
--- /dev/null
+++ b/src/com/d_project/qrcode/QRData.as
@@ -0,0 +1,85 @@
+package com.d_project.qrcode {
+
+ /**
+ * QRData
+ * @author Kazuhiko Arase
+ */
+ internal class QRData {
+
+ private var mode : int;
+
+ private var data : String;
+
+ public function QRData(mode : int, data : String) {
+ this.mode = mode;
+ this.data = data;
+ }
+
+ public function getMode() : int {
+ return mode;
+ }
+
+ public function getData() : String {
+ return data;
+ }
+
+ public function getLength() : int {
+ throw new Error("not implemented.");
+ }
+
+ public function write(buffer : BitBuffer) : void {
+ throw new Error("not implemented.");
+ }
+
+ /**
+ * åçªåã³ã¢ã¼ãã«å¯¾ãããããé·ãåå¾ããã
+ */
+ public function getLengthInBits(type : int) : int {
+
+ if (1 <= type && type < 10) {
+
+ // 1 - 9
+
+ switch(mode) {
+ case Mode.MODE_NUMBER : return 10;
+ case Mode.MODE_ALPHA_NUM : return 9;
+ case Mode.MODE_8BIT_BYTE : return 8;
+ case Mode.MODE_KANJI : return 8;
+ default :
+ throw new Error("mode:" + mode);
+ }
+
+ } else if (type < 27) {
+
+ // 10 - 26
+
+ switch(mode) {
+ case Mode.MODE_NUMBER : return 12;
+ case Mode.MODE_ALPHA_NUM : return 11;
+ case Mode.MODE_8BIT_BYTE : return 16;
+ case Mode.MODE_KANJI : return 10;
+ default :
+ throw new Error("mode:" + mode);
+ }
+
+ } else if (type < 41) {
+
+ // 27 - 40
+
+ switch(mode) {
+ case Mode.MODE_NUMBER : return 14;
+ case Mode.MODE_ALPHA_NUM : return 13;
+ case Mode.MODE_8BIT_BYTE : return 16;
+ case Mode.MODE_KANJI : return 12;
+ default :
+ throw new Error("mode:" + mode);
+ }
+
+ } else {
+ throw new Error("type:" + type);
+ }
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRKanji.as b/src/com/d_project/qrcode/QRKanji.as
new file mode 100644
index 0000000..4eee788
--- /dev/null
+++ b/src/com/d_project/qrcode/QRKanji.as
@@ -0,0 +1,49 @@
+package com.d_project.qrcode {
+
+ import flash.utils.ByteArray;
+
+ /**
+ * QRKanji
+ * @author Kazuhiko Arase
+ */
+ internal class QRKanji extends QRData {
+
+ public function QRKanji(data : String) {
+ super(Mode.MODE_KANJI, data);
+ }
+
+ public override function write(buffer : BitBuffer) : void {
+
+ var data : ByteArray = StringUtil.getBytes(getData(), QRUtil.getJISEncoding() );
+
+ var i : int = 0;
+
+ while (i + 1 < data.length) {
+
+ var c : int = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);
+
+ if (0x8140 <= c && c <= 0x9FFC) {
+ c -= 0x8140;
+ } else if (0xE040 <= c && c <= 0xEBBF) {
+ c -= 0xC140;
+ } else {
+ throw new Error("illegal char at " + (i + 1) + "/" + c);
+ }
+
+ c = ( (c >>> 8) & 0xff) * 0xC0 + (c & 0xff);
+
+ buffer.put(c, 13);
+
+ i += 2;
+ }
+
+ if (i < data.length) {
+ throw new Error("illegal char at " + (i + 1) );
+ }
+ }
+
+ public override function getLength() : int {
+ return Math.floor(StringUtil.getBytes(getData(), QRUtil.getJISEncoding() ).length / 2);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRMath.as b/src/com/d_project/qrcode/QRMath.as
new file mode 100644
index 0000000..a5c52e8
--- /dev/null
+++ b/src/com/d_project/qrcode/QRMath.as
@@ -0,0 +1,68 @@
+package com.d_project.qrcode {
+
+ /**
+ * QRMath
+ * @author Kazuhiko Arase
+ */
+ internal class QRMath {
+
+ function QRMath() {
+ throw new Error("");
+ }
+
+ private static var EXP_TABLE : Array;
+ private static var LOG_TABLE : Array;
+
+ private static var classInitialized : Boolean = initializeClass();
+
+ private static function initializeClass() : Boolean {
+
+ var i : int;
+
+ EXP_TABLE = new Array(256);
+
+ for (i = 0; i < 8; i++) {
+ EXP_TABLE[i] = 1 << i;
+ }
+
+ for (i = 8; i < 256; i++) {
+ EXP_TABLE[i] = EXP_TABLE[i - 4]
+ ^ EXP_TABLE[i - 5]
+ ^ EXP_TABLE[i - 6]
+ ^ EXP_TABLE[i - 8];
+ }
+
+ LOG_TABLE = new Array(256);
+ for (i = 0; i < 255; i++) {
+ LOG_TABLE[EXP_TABLE[i] ] = i;
+ }
+
+ return true;
+ }
+
+ public static function glog(n : int) : int {
+
+ if (n < 1) {
+ throw new Error("log(" + n + ")");
+ }
+
+ return LOG_TABLE[n];
+ }
+
+ public static function gexp(n : int) : int {
+
+ while (n < 0) {
+ n += 255;
+ }
+
+ while (n >= 256) {
+ n -= 255;
+ }
+
+ return EXP_TABLE[n];
+ }
+
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRNumber.as b/src/com/d_project/qrcode/QRNumber.as
new file mode 100644
index 0000000..146689d
--- /dev/null
+++ b/src/com/d_project/qrcode/QRNumber.as
@@ -0,0 +1,65 @@
+package com.d_project.qrcode {
+
+ /**
+ * QRNumber
+ * @author Kazuhiko Arase
+ */
+ internal class QRNumber extends QRData {
+
+ public function QRNumber(data : String) {
+ super(Mode.MODE_NUMBER, data);
+ }
+
+ public override function write(buffer : BitBuffer) : void {
+
+ var data : String = getData();
+
+ var i : int = 0;
+ var num : int;
+
+ while (i + 2 < data.length) {
+ num = parseInt(data.substring(i, i + 3) );
+ buffer.put(num, 10);
+ i += 3;
+ }
+
+ if (i < data.length) {
+
+ if (data.length - i == 1) {
+ num = parseInt(data.substring(i, i + 1) );
+ buffer.put(num, 4);
+ } else if (data.length - i == 2) {
+ num = parseInt(data.substring(i, i + 2) );
+ buffer.put(num, 7);
+ }
+
+ }
+ }
+
+ public override function getLength() : int {
+ return getData().length;
+ }
+
+ private static function parseInt(s : String) : int {
+ var num : int = 0;
+ for (var i : int = 0; i < s.length; i++) {
+ num = num * 10 + parseCharCode(s.charCodeAt(i) );
+ }
+ return num;
+ }
+
+ private static function parseCharCode(c : int) : int {
+
+ if (getCharCode('0') <= c && c <= getCharCode('9') ) {
+ return c - getCharCode('0') ;
+ }
+
+ throw new Error("illegal char :" + c);
+ }
+
+ private static function getCharCode(c : String) : int {
+ return c.charCodeAt(0);
+ }
+
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/QRUtil.as b/src/com/d_project/qrcode/QRUtil.as
new file mode 100644
index 0000000..bd05994
--- /dev/null
+++ b/src/com/d_project/qrcode/QRUtil.as
@@ -0,0 +1,345 @@
+package com.d_project.qrcode {
+
+ import flash.utils.ByteArray;
+
+ /**
+ * QRUtil
+ * @author Kazuhiko Arase
+ */
+ public class QRUtil {
+
+ public static function getJISEncoding() : String {
+ return "shift_jis";
+ }
+
+ public static function getPatternPosition(typeNumber : int) : Array {
+ return PATTERN_POSITION_TABLE[typeNumber - 1];
+ }
+
+ private static var PATTERN_POSITION_TABLE : Array =[
+ [],
+ [6, 18],
+ [6, 22],
+ [6, 26],
+ [6, 30],
+ [6, 34],
+ [6, 22, 38],
+ [6, 24, 42],
+ [6, 26, 46],
+ [6, 28, 50],
+ [6, 30, 54],
+ [6, 32, 58],
+ [6, 34, 62],
+ [6, 26, 46, 66],
+ [6, 26, 48, 70],
+ [6, 26, 50, 74],
+ [6, 30, 54, 78],
+ [6, 30, 56, 82],
+ [6, 30, 58, 86],
+ [6, 34, 62, 90],
+ [6, 28, 50, 72, 94],
+ [6, 26, 50, 74, 98],
+ [6, 30, 54, 78, 102],
+ [6, 28, 54, 80, 106],
+ [6, 32, 58, 84, 110],
+ [6, 30, 58, 86, 114],
+ [6, 34, 62, 90, 118],
+ [6, 26, 50, 74, 98, 122],
+ [6, 30, 54, 78, 102, 126],
+ [6, 26, 52, 78, 104, 130],
+ [6, 30, 56, 82, 108, 134],
+ [6, 34, 60, 86, 112, 138],
+ [6, 30, 58, 86, 114, 142],
+ [6, 34, 62, 90, 118, 146],
+ [6, 30, 54, 78, 102, 126, 150],
+ [6, 24, 50, 76, 102, 128, 154],
+ [6, 28, 54, 80, 106, 132, 158],
+ [6, 32, 58, 84, 110, 136, 162],
+ [6, 26, 54, 82, 110, 138, 166],
+ [6, 30, 58, 86, 114, 142, 170]
+ ];
+
+ private static var MAX_LENGTH : Array = [
+ [ [41, 25, 17, 10], [34, 20, 14, 8], [27, 16, 11, 7], [17, 10, 7, 4] ],
+ [ [77, 47, 32, 20], [63, 38, 26, 16], [48, 29, 20, 12], [34, 20, 14, 8] ],
+ [ [127, 77, 53, 32], [101, 61, 42, 26], [77, 47, 32, 20], [58, 35, 24, 15] ],
+ [ [187, 114, 78, 48], [149, 90, 62, 38], [111, 67, 46, 28], [82, 50, 34, 21] ],
+ [ [255, 154, 106, 65], [202, 122, 84, 52], [144, 87, 60, 37], [106, 64, 44, 27] ],
+ [ [322, 195, 134, 82], [255, 154, 106, 65], [178, 108, 74, 45], [139, 84, 58, 36] ],
+ [ [370, 224, 154, 95], [293, 178, 122, 75], [207, 125, 86, 53], [154, 93, 64, 39] ],
+ [ [461, 279, 192, 118], [365, 221, 152, 93], [259, 157, 108, 66], [202, 122, 84, 52] ],
+ [ [552, 335, 230, 141], [432, 262, 180, 111], [312, 189, 130, 80], [235, 143, 98, 60] ],
+ [ [652, 395, 271, 167], [513, 311, 213, 131], [364, 221, 151, 93], [288, 174, 119, 74] ]
+ ];
+
+ public static function getMaxLength(typeNumber : int, mode : int, errorCorrectLevel : int) : int {
+
+ var t : int = typeNumber - 1;
+ var e : int = 0;
+ var m : int = 0;
+
+ switch(errorCorrectLevel) {
+ case ErrorCorrectLevel.L : e = 0; break;
+ case ErrorCorrectLevel.M : e = 1; break;
+ case ErrorCorrectLevel.Q : e = 2; break;
+ case ErrorCorrectLevel.H : e = 3; break;
+ default :
+ throw new Error("e:" + errorCorrectLevel);
+ }
+
+ switch(mode) {
+ case Mode.MODE_NUMBER : m = 0; break;
+ case Mode.MODE_ALPHA_NUM : m = 1; break;
+ case Mode.MODE_8BIT_BYTE : m = 2; break;
+ case Mode.MODE_KANJI : m = 3; break;
+ default :
+ throw new Error("m:" + mode);
+ }
+
+ return MAX_LENGTH[t][e][m];
+ }
+
+
+ /**
+ * ã¨ã©ã¼è¨æ£å¤é
å¼ãåå¾ããã
+ */
+ public static function getErrorCorrectPolynomial(errorCorrectLength : int) : Polynomial{
+
+ var a : Polynomial = new Polynomial([1]);
+
+ for (var i : int = 0; i < errorCorrectLength; i++) {
+ a = a.multiply(new Polynomial([1, QRMath.gexp(i)]) );
+ }
+
+ return a;
+ }
+
+ /**
+ * æå®ããããã¿ã¼ã³ã®ãã¹ã¯ãåå¾ããã
+ */
+ public static function getMask(maskPattern : int, i : int, j : int) : Boolean {
+
+ switch (maskPattern) {
+
+ case MaskPattern.PATTERN000 : return (i + j) % 2 == 0;
+ case MaskPattern.PATTERN001 : return i % 2 == 0;
+ case MaskPattern.PATTERN010 : return j % 3 == 0;
+ case MaskPattern.PATTERN011 : return (i + j) % 3 == 0;
+ case MaskPattern.PATTERN100 : return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0;
+ case MaskPattern.PATTERN101 : return (i * j) % 2 + (i * j) % 3 == 0;
+ case MaskPattern.PATTERN110 : return ( (i * j) % 2 + (i * j) % 3) % 2 == 0;
+ case MaskPattern.PATTERN111 : return ( (i * j) % 3 + (i + j) % 2) % 2 == 0;
+
+ default :
+ throw new Error("mask:" + maskPattern);
+ }
+ }
+
+ /**
+ * 失ç¹ãåå¾ãã
+ */
+ public static function getLostPoint(qrCode : QRCode) : int {
+
+ var moduleCount : int = qrCode.getModuleCount();
+
+ var lostPoint : int = 0;
+
+ var row : int;
+ var col : int;
+
+ // LEVEL1
+
+ for (row = 0; row < moduleCount; row++) {
+
+ for (col = 0; col < moduleCount; col++) {
+
+ var sameCount : int = 0;
+ var dark : Boolean = qrCode.isDark(row, col);
+
+ for (var r : int = -1; r <= 1; r++) {
+
+ if (row + r < 0 || moduleCount <= row + r) {
+ continue;
+ }
+
+ for (var c : int = -1; c <= 1; c++) {
+
+ if (col + c < 0 || moduleCount <= col + c) {
+ continue;
+ }
+
+ if (r == 0 && c == 0) {
+ continue;
+ }
+
+ if (dark == qrCode.isDark(row + r, col + c) ) {
+ sameCount++;
+ }
+ }
+ }
+
+ if (sameCount > 5) {
+ lostPoint += (3 + sameCount - 5);
+ }
+ }
+ }
+
+ // LEVEL2
+
+ for (row = 0; row < moduleCount - 1; row++) {
+ for (col = 0; col < moduleCount - 1; col++) {
+ var count : int = 0;
+ if (qrCode.isDark(row, col ) ) count++;
+ if (qrCode.isDark(row + 1, col ) ) count++;
+ if (qrCode.isDark(row, col + 1) ) count++;
+ if (qrCode.isDark(row + 1, col + 1) ) count++;
+ if (count == 0 || count == 4) {
+ lostPoint += 3;
+ }
+ }
+ }
+
+ // LEVEL3
+
+ for (row = 0; row < moduleCount; row++) {
+ for (col = 0; col < moduleCount - 6; col++) {
+ if (qrCode.isDark(row, col)
+ && !qrCode.isDark(row, col + 1)
+ && qrCode.isDark(row, col + 2)
+ && qrCode.isDark(row, col + 3)
+ && qrCode.isDark(row, col + 4)
+ && !qrCode.isDark(row, col + 5)
+ && qrCode.isDark(row, col + 6) ) {
+ lostPoint += 40;
+ }
+ }
+ }
+
+ for (col = 0; col < moduleCount; col++) {
+ for (row = 0; row < moduleCount - 6; row++) {
+ if (qrCode.isDark(row, col)
+ && !qrCode.isDark(row + 1, col)
+ && qrCode.isDark(row + 2, col)
+ && qrCode.isDark(row + 3, col)
+ && qrCode.isDark(row + 4, col)
+ && !qrCode.isDark(row + 5, col)
+ && qrCode.isDark(row + 6, col) ) {
+ lostPoint += 40;
+ }
+ }
+ }
+
+ // LEVEL4
+
+ var darkCount : int = 0;
+
+ for (col = 0; col < moduleCount; col++) {
+ for (row = 0; row < moduleCount; row++) {
+ if (qrCode.isDark(row, col) ) {
+ darkCount++;
+ }
+ }
+ }
+
+ var ratio : int = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5;
+ lostPoint += ratio * 10;
+
+ return lostPoint;
+ }
+
+ public static function getMode(s : String) : int {
+ if (isAlphaNum(s) ) {
+ if (isNumber(s) ) {
+ return Mode.MODE_NUMBER;
+ }
+ return Mode.MODE_ALPHA_NUM;
+ } else if (isKanji(s) ) {
+ return Mode.MODE_KANJI;
+ } else {
+ return Mode.MODE_8BIT_BYTE;
+ }
+ }
+
+ private static function isNumber(s : String) : Boolean {
+ for (var i : int = 0; i < s.length; i++) {
+ var c : String = s.charAt(i);
+ if (!('0' <= c && c <= '9') ) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static function isAlphaNum(s : String) : Boolean {
+ for (var i : int = 0; i < s.length; i++) {
+ var c : String = s.charAt(i);
+ if (!('0' <= c && c <= '9') && !('A' <= c && c <= 'Z') && " $%*+-./:".indexOf(c) == -1) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static function isKanji(s : String) : Boolean {
+
+ var data : ByteArray = StringUtil.getBytes(s, QRUtil.getJISEncoding() );
+
+ var i : int = 0;
+
+ while (i + 1 < data.length) {
+
+ var c : int = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);
+
+ if (!(0x8140 <= c && c <= 0x9FFC) && !(0xE040 <= c && c <= 0xEBBF) ) {
+ return false;
+ }
+
+ i += 2;
+ }
+
+ if (i < data.length) {
+ return false;
+ }
+
+ return true;
+ }
+
+ private static const G15 : int = (1 << 10) | (1 << 8) | (1 << 5)
+ | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
+
+ private static const G18 : int = (1 << 12) | (1 << 11) | (1 << 10)
+ | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
+
+ private static const G15_MASK : int = (1 << 14) | (1 << 12) | (1 << 10)
+ | (1 << 4) | (1 << 1);
+
+ public static function getBCHTypeInfo(data : int) : int {
+ var d : int = data << 10;
+ while (getBCHDigit(d) - getBCHDigit(G15) >= 0) {
+ d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15) ) );
+ }
+ return ( (data << 10) | d) ^ G15_MASK;
+ }
+
+ public static function getBCHTypeNumber(data : int) : int {
+ var d : int = data << 12;
+ while (getBCHDigit(d) - getBCHDigit(G18) >= 0) {
+ d ^= (G18 << (getBCHDigit(d) - getBCHDigit(G18) ) );
+ }
+ return (data << 12) | d;
+ }
+
+ private static function getBCHDigit(data : int) : int {
+
+ var digit : int = 0;
+
+ while (data != 0) {
+ digit++;
+ data >>>= 1;
+ }
+
+ return digit;
+
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/RSBlock.as b/src/com/d_project/qrcode/RSBlock.as
new file mode 100644
index 0000000..c53c5be
--- /dev/null
+++ b/src/com/d_project/qrcode/RSBlock.as
@@ -0,0 +1,139 @@
+package com.d_project.qrcode {
+
+ /**
+ * RSBlock
+ * @author Kazuhiko Arase
+ */
+ internal class RSBlock {
+
+ private static var RS_BLOCK_TABLE : Array = [
+
+ // L
+ // M
+ // Q
+ // H
+
+ // 1
+ [1, 26, 19],
+ [1, 26, 16],
+ [1, 26, 13],
+ [1, 26, 9],
+
+ // 2
+ [1, 44, 34],
+ [1, 44, 28],
+ [1, 44, 22],
+ [1, 44, 16],
+
+ // 3
+ [1, 70, 55],
+ [1, 70, 44],
+ [2, 35, 17],
+ [2, 35, 13],
+
+ // 4
+ [1, 100, 80],
+ [2, 50, 32],
+ [2, 50, 24],
+ [4, 25, 9],
+
+ // 5
+ [1, 134, 108],
+ [2, 67, 43],
+ [2, 33, 15, 2, 34, 16],
+ [2, 33, 11, 2, 34, 12],
+
+ // 6
+ [2, 86, 68],
+ [4, 43, 27],
+ [4, 43, 19],
+ [4, 43, 15],
+
+ // 7
+ [2, 98, 78],
+ [4, 49, 31],
+ [2, 32, 14, 4, 33, 15],
+ [4, 39, 13, 1, 40, 14],
+
+ // 8
+ [2, 121, 97],
+ [2, 60, 38, 2, 61, 39],
+ [4, 40, 18, 2, 41, 19],
+ [4, 40, 14, 2, 41, 15],
+
+ // 9
+ [2, 146, 116],
+ [3, 58, 36, 2, 59, 37],
+ [4, 36, 16, 4, 37, 17],
+ [4, 36, 12, 4, 37, 13],
+
+ // 10
+ [2, 86, 68, 2, 87, 69],
+ [4, 69, 43, 1, 70, 44],
+ [6, 43, 19, 2, 44, 20],
+ [6, 43, 15, 2, 44, 16]
+
+ ];
+
+ private var totalCount : int;
+ private var dataCount : int;
+
+ public function RSBlock(totalCount : int, dataCount : int) {
+ this.totalCount = totalCount;
+ this.dataCount = dataCount;
+ }
+
+ public function getDataCount() : int {
+ return dataCount;
+ }
+
+ public function getTotalCount() : int {
+ return totalCount;
+ }
+
+ public static function getRSBlocks(typeNumber : int, errorCorrectLevel : int) : Array {
+
+ var rsBlock : Array = getRsBlockTable(typeNumber, errorCorrectLevel);
+ var length : int = Math.floor(rsBlock.length / 3);
+ var list : Array = new Array();
+
+ for (var i : int = 0; i < length; i++) {
+
+ var count : int = rsBlock[i * 3 + 0];
+ var totalCount : int = rsBlock[i * 3 + 1];
+ var dataCount : int = rsBlock[i * 3 + 2];
+
+ for (var j : int = 0; j < count; j++) {
+ list.push(new RSBlock(totalCount, dataCount) );
+ }
+ }
+
+ return list;
+ }
+
+ private static function getRsBlockTable(typeNumber : int, errorCorrectLevel : int) : Array {
+
+ try {
+
+ switch(errorCorrectLevel) {
+ case ErrorCorrectLevel.L :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
+ case ErrorCorrectLevel.M :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
+ case ErrorCorrectLevel.Q :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
+ case ErrorCorrectLevel.H :
+ return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
+ default :
+ break;
+ }
+
+ } catch(e : Error) {
+ }
+
+ throw new Error("tn:" + typeNumber + "/ecl:" + errorCorrectLevel);
+ }
+
+ }
+
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/StringUtil.as b/src/com/d_project/qrcode/StringUtil.as
new file mode 100644
index 0000000..ae94888
--- /dev/null
+++ b/src/com/d_project/qrcode/StringUtil.as
@@ -0,0 +1,17 @@
+package com.d_project.qrcode {
+
+ import flash.utils.ByteArray;
+
+ /**
+ * StringUtil
+ * @author Kazuhiko Arase
+ */
+ internal class StringUtil {
+
+ public static function getBytes(s : String, encoding : String) : ByteArray {
+ var b : ByteArray = new ByteArray();
+ b.writeMultiByte(s, encoding);
+ return b;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/com/d_project/qrcode/mx/QRCode.as b/src/com/d_project/qrcode/mx/QRCode.as
new file mode 100644
index 0000000..ba74e14
--- /dev/null
+++ b/src/com/d_project/qrcode/mx/QRCode.as
@@ -0,0 +1,67 @@
+package com.d_project.qrcode.mx {
+
+ import mx.core.UIComponent;
+ import flash.display.Graphics;
+
+ import com.d_project.qrcode.ErrorCorrectLevel;
+
+
+ /**
+ * QRCode
+ * @author Kazuhiko Arase
+ */
+ public class QRCode extends UIComponent {
+
+ private var qr : com.d_project.qrcode.QRCode;
+
+ private var _text : String;
+
+ [Inspectable(enumeration="L,M,Q,H", defaultValue="H")]
+ public var errorCorrectLevel : String = "H";
+
+ public function QRCode() {
+ _text = "QRCode";
+ qr = null;
+ }
+
+ public function get text() : String {
+ return _text;
+ }
+
+ public function set text(value : String) : void {
+ _text = value;
+ qr = null;
+ invalidateDisplayList();
+ }
+
+ protected override function updateDisplayList(unscaledWidth : Number, unscaledHeight : Number) : void {
+
+ var padding : Number = 10;
+
+ var size : Number = Math.min(unscaledWidth, unscaledHeight) - padding * 2;
+ var xOffset : Number = (unscaledWidth - size) / 2;
+ var yOffset : Number = (unscaledHeight - size) / 2;
+
+ if (qr == null) {
+ qr = com.d_project.qrcode.QRCode.getMinimumQRCode(text, ErrorCorrectLevel[errorCorrectLevel]);
+ }
+
+ var cs : Number = size / qr.getModuleCount();
+
+ var g : Graphics = graphics;
+
+ g.beginFill(0xffffff);
+ g.drawRect(0, 0, unscaledWidth, unscaledHeight);
+ g.endFill();
+
+ for (var row : int = 0; row < qr.getModuleCount(); row++) {
+ for (var col : int = 0; col < qr.getModuleCount(); col++) {
+ g.beginFill( (qr.isDark(row, col)? 0 : 0xffffff) );
+ g.drawRect(cs * col + xOffset, cs * row + yOffset, cs, cs);
+ g.endFill();
+ }
+ }
+ }
+ }
+}
+
|
hotchpotch/as3rails2u
|
0809927b4269a8777d8117b8fa8eff617306e8d9
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@28 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/mx/mxTweener.as b/src/com/rails2u/mx/mxTweener.as
index 29d0d19..57d4a79 100644
--- a/src/com/rails2u/mx/mxTweener.as
+++ b/src/com/rails2u/mx/mxTweener.as
@@ -1,108 +1,194 @@
package com.rails2u.mx {
import mx.effects.Effect;
import mx.effects.AnimateProperty;
import mx.effects.easing.*;
+ import mx.effects.*;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import mx.events.TweenEvent;
import mx.effects.Blur;
import mx.effects.Rotate;
import mx.utils.DescribeTypeCache;
import mx.utils.DescribeTypeCacheRecord;
import mx.effects.Parallel;
+ import mx.effects.CompositeEffect;
+ import mx.effects.Sequence;
+ import mx.core.mx_internal;
+ import mx.events.EffectEvent;
+ import mx.effects.effectClasses.TweenEffectInstance;
+ import mx.effects.TweenEffect;
+ use namespace mx_internal;
+ /*
+ * prop ¤Ï¤ï¤±¤è¤¦
+ */
public class mxTweener {
private static const EASYING_CLASSES:Array = [
Back, Circular, Elastic, Quartic, Sine,
Bounce, Cubic, Exponential, Quadratic, Quintic
];
+ private static const TWEEN_EFFECT_CLASSES:Array = [
+ AnimateProperty, Blur, Dissolve, Fade, Glow, Move, Pause, Resize, Rotate, Zoom
+ ];
+
public static const EASYING_FUNCTIONS:Object = createEasyingFunctions();
private static function createEasyingFunctions():Object {
var o:Object = {};
o['linear'] = Linear.easeNone;
for each(var klass:Object in EASYING_CLASSES) {
var name:String = getQualifiedClassName(klass).replace(/^.*::/,'').toLocaleLowerCase();
o['easein' + name] = klass['easeIn'];
o['easeout' + name] = klass['easeOut'];
o['easeinout' + name] = klass['easeInOut'];
}
return o;
}
- public static function addTween(options:Object):Effect {
- var pa:Parallel = new Parallel();
+ public static function tween(... args):Effect {
+ if(args.length == 1) {
+ if(args[0] is Array) {
+ var par:Parallel= new Parallel;
+ for each (var options:Object in args[0]) {
+ par.addChild(factoryTween(options));
+ }
+ return par;
+ } else {
+ return factoryTween(args[0]);
+ }
+ }
+ if(args.length > 1) {
+ var seq:Sequence = new Sequence;
+ for each (options in args) {
+ seq.addChild(factoryTween(options));
+ }
+ return seq;
+ }
+ return new CompositeEffect;
+ }
+
+ public static function factoryTween(options:Object):Effect {
+ if (options.properties) {
+ return animatePropertyTween(options);
+ } else {
+ return effectTween(options);
+ }
+ }
+
+ public static function effectTween(options:Object):Effect {
+ var klass:Class;
+ if(options.klass as Class) {
+ klass = options.klass;
+ } else {
+ klass = Class(getDefinitionByName('mx.effects.' + options.klass));
+ }
+ var ef:Effect = new klass();
- var ef:AnimateProperty = new AnimateProperty();
var desc:XML = DescribeTypeCache.describeType(ef).typeDescription;
var effectOptions:Object = {};
-
- for (var key:String in options) {
+ var key:String;
+ for (key in options) {
if(
desc.variable.(@name == key)[email protected]() ||
desc.accessor.(@name == key && @access == 'readwrite')[email protected]()
) {
effectOptions[key] = options[key];
delete options[key];
}
}
-
if (options.easing is Function) {
effectOptions.easingFunction = options.easing;
- delete options.easing;
} else if (options.easing is String){
effectOptions.easingFunction = EASYING_FUNCTIONS[options.easing.toLocaleLowerCase()];
- delete options.easing;
}
- var repeatReverseFlag:Boolean = false;
- if (options.repeatReverse) {
- repeatReverseFlag = true;
- delete options.repeatReverse;
+ ef = createEffect(klass, effectOptions);
+ if(options.repeatReverse) {
+ if(ef.repeatCount != 0) {
+ ef.addEventListener(TweenEvent.TWEEN_START,
+ createRepeatCountHandler(ef.repeatCount));
+ ef.repeatCount = 0;
+ }
+ ef.addEventListener(TweenEvent.TWEEN_END, tweenReverseHandler);
}
+ return ef;
+ }
- if (options.properties) {
- var props:Object = options.properties;
- delete options.properties;
- for (var key:String in props) {
- options[key] = props[key];
+ public static function animatePropertyTween(options:Object):Parallel {
+ var parallel:Parallel = new Parallel();
+
+ var ef:AnimateProperty = new AnimateProperty();
+ var desc:XML = DescribeTypeCache.describeType(ef).typeDescription;
+ var effectOptions:Object = {};
+
+ var key:String;
+ for (key in options) {
+ if(
+ desc.variable.(@name == key)[email protected]() ||
+ desc.accessor.(@name == key && @access == 'readwrite')[email protected]()
+ ) {
+ effectOptions[key] = options[key];
+ delete options[key];
}
- };
+ }
- for (var key:String in options) {
- var effect:AnimateProperty = createAnimateProperty(effectOptions);
+ if (options.easing is Function) {
+ effectOptions.easingFunction = options.easing;
+ } else if (options.easing is String){
+ effectOptions.easingFunction = EASYING_FUNCTIONS[options.easing.toLocaleLowerCase()];
+ }
+
+ var properties:Object = options.properties;
+ for (key in properties) {
+ var effect:AnimateProperty = AnimateProperty(createEffect(AnimateProperty, effectOptions));
effect.property = key;
- if (options[key] is Array) {
- effect.fromValue = options[key][0];
- effect.toValue = options[key][1];
+ if (properties[key] is Array) {
+ effect.fromValue = properties[key][0];
+ effect.toValue = properties[key][1];
} else {
- effect.toValue = options[key];
+ effect.toValue = properties[key];
}
- pa.addChild(effect);
+ parallel.addChild(effect);
}
- if(repeatReverseFlag) {
- for each(var eff:Effect in pa.children) {
+ if(options.repeatReverse) {
+ for each(var eff:Effect in parallel.children) {
// eff.repeatCount = 0;
+ // dirty code... :(
+ if(eff.repeatCount != 0) {
+ eff.addEventListener(TweenEvent.TWEEN_START,
+ createRepeatCountHandler(eff.repeatCount));
+ eff.repeatCount = 0;
+ }
eff.addEventListener(TweenEvent.TWEEN_END, tweenReverseHandler);
}
}
- return Effect(pa);
+ return parallel;
}
- private static function createAnimateProperty(effectOptions:Object):AnimateProperty {
- var ef:AnimateProperty = new AnimateProperty();
+ private static function createRepeatCountHandler(origRepCount:uint):Function {
+ var repCount:uint = 0;
+ return function(e:TweenEvent):void {
+ if(origRepCount == repCount++) {
+ e.currentTarget.end();
+ repCount = 0;
+ }
+ }
+ }
+
+ private static function createEffect(klass:Class, effectOptions:Object):Effect {
+ var ef:Effect = new klass();
for (var key:String in effectOptions) {
ef[key] = effectOptions[key];
}
return ef;
}
private static function tweenReverseHandler(e:TweenEvent):void {
- e.target.reverse();
+ e.currentTarget.reverse();
}
}
}
|
hotchpotch/as3rails2u
|
96722804b9f55407089b401a21a0e7ec391e9a72
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@27 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/mx/mxTweener.as b/src/com/rails2u/mx/mxTweener.as
new file mode 100644
index 0000000..29d0d19
--- /dev/null
+++ b/src/com/rails2u/mx/mxTweener.as
@@ -0,0 +1,108 @@
+package com.rails2u.mx {
+ import mx.effects.Effect;
+ import mx.effects.AnimateProperty;
+ import mx.effects.easing.*;
+ import flash.utils.getDefinitionByName;
+ import flash.utils.getQualifiedClassName;
+ import mx.events.TweenEvent;
+ import mx.effects.Blur;
+ import mx.effects.Rotate;
+ import mx.utils.DescribeTypeCache;
+ import mx.utils.DescribeTypeCacheRecord;
+ import mx.effects.Parallel;
+
+ public class mxTweener {
+ private static const EASYING_CLASSES:Array = [
+ Back, Circular, Elastic, Quartic, Sine,
+ Bounce, Cubic, Exponential, Quadratic, Quintic
+ ];
+
+ public static const EASYING_FUNCTIONS:Object = createEasyingFunctions();
+
+ private static function createEasyingFunctions():Object {
+ var o:Object = {};
+ o['linear'] = Linear.easeNone;
+ for each(var klass:Object in EASYING_CLASSES) {
+ var name:String = getQualifiedClassName(klass).replace(/^.*::/,'').toLocaleLowerCase();
+ o['easein' + name] = klass['easeIn'];
+ o['easeout' + name] = klass['easeOut'];
+ o['easeinout' + name] = klass['easeInOut'];
+ }
+ return o;
+ }
+
+ public static function addTween(options:Object):Effect {
+ var pa:Parallel = new Parallel();
+
+ var ef:AnimateProperty = new AnimateProperty();
+ var desc:XML = DescribeTypeCache.describeType(ef).typeDescription;
+ var effectOptions:Object = {};
+
+ for (var key:String in options) {
+ if(
+ desc.variable.(@name == key)[email protected]() ||
+ desc.accessor.(@name == key && @access == 'readwrite')[email protected]()
+ ) {
+ effectOptions[key] = options[key];
+ delete options[key];
+ }
+ }
+
+
+ if (options.easing is Function) {
+ effectOptions.easingFunction = options.easing;
+ delete options.easing;
+ } else if (options.easing is String){
+ effectOptions.easingFunction = EASYING_FUNCTIONS[options.easing.toLocaleLowerCase()];
+ delete options.easing;
+ }
+
+ var repeatReverseFlag:Boolean = false;
+ if (options.repeatReverse) {
+ repeatReverseFlag = true;
+ delete options.repeatReverse;
+ }
+
+ if (options.properties) {
+ var props:Object = options.properties;
+ delete options.properties;
+ for (var key:String in props) {
+ options[key] = props[key];
+ }
+ };
+
+ for (var key:String in options) {
+ var effect:AnimateProperty = createAnimateProperty(effectOptions);
+ effect.property = key;
+ if (options[key] is Array) {
+ effect.fromValue = options[key][0];
+ effect.toValue = options[key][1];
+ } else {
+ effect.toValue = options[key];
+ }
+ pa.addChild(effect);
+ }
+
+ if(repeatReverseFlag) {
+ for each(var eff:Effect in pa.children) {
+ // eff.repeatCount = 0;
+ eff.addEventListener(TweenEvent.TWEEN_END, tweenReverseHandler);
+ }
+ }
+
+ return Effect(pa);
+ }
+
+ private static function createAnimateProperty(effectOptions:Object):AnimateProperty {
+ var ef:AnimateProperty = new AnimateProperty();
+ for (var key:String in effectOptions) {
+ ef[key] = effectOptions[key];
+ }
+ return ef;
+ }
+
+ private static function tweenReverseHandler(e:TweenEvent):void {
+ e.target.reverse();
+ }
+ }
+}
|
hotchpotch/as3rails2u
|
dc9063c2e741ff8e22fb6086ff5a4bc95ccdd515
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@26 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/utils/BitmapUtil.as b/src/com/rails2u/utils/BitmapUtil.as
index 3b8929e..08e2087 100644
--- a/src/com/rails2u/utils/BitmapUtil.as
+++ b/src/com/rails2u/utils/BitmapUtil.as
@@ -1,22 +1,22 @@
package com.rails2u.utils {
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Matrix;
public class BitmapUtil {
- public static function mozaic(bd:BitmapData, scale:Number = 10, doubleParam:Number = 1.05):BitmapData {
+ public static function mozaic(bd:BitmapData, scale:Number = 10, doubleParam:Number = 1.00):BitmapData {
var tmp:Bitmap = new Bitmap();
var miniBD:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, 0x00FFFFF);
var mozBD:BitmapData = new BitmapData(bd.width, bd.height, true, 0x00FFFFFF);
tmp.bitmapData = bd.clone();
miniBD.draw(tmp, new Matrix(1/scale,0,0,1/scale,0,0));
tmp.bitmapData = miniBD;
mozBD.draw(tmp, new Matrix(scale * doubleParam,0,0,scale * doubleParam,0,0));
return mozBD;
}
}
}
|
hotchpotch/as3rails2u
|
56c60744538602fab42c9b3ca2717a2226050e5a
|
git-svn-id: http://svn.rails2u.com/as3rails2u/trunk@25 96db6a20-122f-0410-8d9f-89437bbe4005
|
diff --git a/src/com/rails2u/utils/BitmapUtil.as b/src/com/rails2u/utils/BitmapUtil.as
new file mode 100644
index 0000000..3b8929e
--- /dev/null
+++ b/src/com/rails2u/utils/BitmapUtil.as
@@ -0,0 +1,22 @@
+package com.rails2u.utils {
+ import flash.display.BitmapData;
+ import flash.display.Bitmap;
+ import flash.geom.Matrix;
+
+ public class BitmapUtil {
+ public static function mozaic(bd:BitmapData, scale:Number = 10, doubleParam:Number = 1.05):BitmapData {
+ var tmp:Bitmap = new Bitmap();
+ var miniBD:BitmapData = new BitmapData(bd.width/scale, bd.height/scale, true, 0x00FFFFF);
+ var mozBD:BitmapData = new BitmapData(bd.width, bd.height, true, 0x00FFFFFF);
+
+ tmp.bitmapData = bd.clone();
+
+ miniBD.draw(tmp, new Matrix(1/scale,0,0,1/scale,0,0));
+ tmp.bitmapData = miniBD;
+
+ mozBD.draw(tmp, new Matrix(scale * doubleParam,0,0,scale * doubleParam,0,0));
+
+ return mozBD;
+ }
+ }
+}
diff --git a/src/log.as b/src/log.as
index d8096bb..b57bae0 100644
--- a/src/log.as
+++ b/src/log.as
@@ -1,23 +1,24 @@
package {
import flash.external.ExternalInterface;
import com.rails2u.utils.ObjectInspecter;
/**
* log() is Object inspect dump output to trace() and use
* Browser(FireFox, Safari and more) External API console.log.
*
* example
* <listing version="3.0">
* var a:Array = [[1,2,3], [4,[5,6]]];
* var sprite:Sprite = new Sprite;
* log(a, sprite);
* # output
* [[1, 2, 3], [4, [5, 6]]], #<flash.display::Sprite:[object Sprite]>
* </listing>
*/
- public function log(... args):void {
+ public function log(... args):String {
var r:String = ObjectInspecter.inspect.apply(null, args);
trace(r)
ExternalInterface.call('console.log', r);
+ return r;
}
}
|
calmh/Register
|
1eccf323c69724214b427737b8ad5a73e5856daa
|
Bump version number to 2.0.12.
|
diff --git a/config/environment.rb b/config/environment.rb
index bf3a34b..e076cb7 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,95 +1,95 @@
# 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.3.9' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
-CURRENT_VERSION = "2.0.11"
+CURRENT_VERSION = "2.0.12"
# 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.
config.gem "authlogic", :version => "2.1.6"
config.gem "fastercsv", :version => "1.5.3"
config.gem "factory_girl", :version => "1.3.1"
config.gem "webrat", :version => "0.7.1"
config.gem "haml", :version => "3.0.18"
# 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 = :sv
# 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 = {
:key => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
54232fb3f6d3a4ec2c7793759da21b732d2a2b58
|
Don't save students that fail validation!
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index b6a5b6a..5cdc6dd 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,338 +1,331 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = [ "archived = 0" ]
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
- set_initial_password
+ @student.password = @student.password_confirmation = ActiveSupport::SecureRandom.hex(16)
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def archive
@student = Student.find(params[:id])
@student.archived = 1
@student.save
redirect_to(@student.club)
end
def unarchive
@student = Student.find(params[:id])
@student.archived = 0
@student.save
redirect_to archived_club_students_path(@student.club)
end
def archived
@club = Club.find(params[:club_id])
@students = @club.students.archived
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to].keys
cur_ids = @student.mailing_list_ids
cur_ids.each do |list_id|
if !ml_ids.include? list_id
ml = MailingList.find(list_id)
@student.mailing_lists.delete(ml)
end
end
ml_ids.each do |list_id|
next if cur_ids.include? list_id
ml = MailingList.find(list_id)
if ( ml.club == nil || ml.club == @club ) &&
( ml.security == 'public' ||
( ml.security == 'private' && current_user.edit_club_permission?(@club) ) ||
( ml.security == 'admin' && current_user.mailinglists_permission? ) )
@student.mailing_lists << ml
end
end
end
end
-
- def set_initial_password
- # This is an ugly hack that uses the random perishable token as a base password for the user.
- @student.reset_perishable_token!
- @student.password = @student.password_confirmation = @student.perishable_token
- @student.reset_perishable_token!
- end
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index 95a9a32..40c1e68 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,312 +1,339 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
test "student page should show all students" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should show only this club's students" do
other_club = Factory(:club)
other_students = 10.times.map { Factory(:student, :club => other_club )}
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
other_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
archived_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "archived page should display only archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "Archived"
@students.each do |s|
assert_not_contain Regexp.new("\\b" + s.name + "\\b")
end
archived_students.each do |s|
assert_contain Regexp.new("\\b" + s.name + "\\b")
end
end
test "unarchive student should remove him/her from archived page" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "Archived"
visit "/students/#{archived_students[0].id}/unarchive"
assert_not_contain Regexp.new("\\b" + archived_students[0].name + "\\b")
archived_students.delete_at 0
archived_students.each do |s|
assert_contain Regexp.new("\\b" + s.name + "\\b")
end
end
test "overview page student count should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
assert_contain Regexp.new("\\b#{@students.length}\\b")
assert_not_contain Regexp.new("\\b#{@students.length + archived_students.length}\\b")
end
test "student should be archived and then not be listed on the club page" do
archived = @students[0]
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link archived.name
click_link "Edit"
click_link "Archive"
click_link @club.name
assert_not_contain archived.name
end
test "should not create new blank student" do
log_in_as_admin
+ before_students = Student.count
click_link "Clubs"
click_link @club.name
click_link "New student"
click_button "Save"
+ after_students = Student.count
assert_not_contain "created"
assert_contain "can't be blank"
+ assert_equal before_students, after_students
end
test "should create new student with minimal info" do
log_in_as_admin
+ before_students = Student.count
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
select @category.category
+
click_button "Save"
+ after_students = Student.count
assert_contain "created"
+ assert_equal before_students + 1, after_students
+ end
+
+ test "should not create new student with bad birthdate" do
+ log_in_as_admin
+ before_students = Student.count
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19859293"
+ select @category.category
+
+ click_button "Save"
+ after_students = Student.count
+
+ assert_not_contain "created"
+ assert_contain "invalid"
+ assert_equal before_students, after_students
end
test "should create a new student in x groups" do
@admin.groups_permission = true
@admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_groups.each do |g|
check g.identifier
end
click_button "Save"
assert_contain "created"
member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_contain "Test Testsson"
end
non_member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_not_contain "Test Testsson"
end
end
test "should create a new student in x mailing lists" do
@admin.mailinglists_permission = true
@admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_lists.each do |m|
check m.description
end
click_button "Save"
assert_contain "created"
member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_contain "Test Testsson"
end
non_member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_not_contain "Test Testsson"
end
end
test "new student should join club mailing list per default" do
mailing_list = Factory(:mailing_list, :default => 1)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
other_club = Factory(:club)
mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_not_contain "Test Testsson"
end
test "student should be able to edit self without losing groups" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
group = Factory(:group)
student.groups << group;
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.groups.length == 1
end
test "student should join mailing list" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_list = Factory(:mailing_list)
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_list.description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == [ mailing_list.id ]
end
test "student should join one mailing list and leave another" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
end
test "student leave all mailing lists" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
uncheck mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == []
end
end
|
calmh/Register
|
60f99b871216aae2ff70246ed9e873c3536d8c67
|
Upgrade to Rails 2.3.9 and newer authlogic and haml gems.
|
diff --git a/config/environment.rb b/config/environment.rb
index 57fb194..bf3a34b 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,95 +1,95 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
+RAILS_GEM_VERSION = '2.3.9' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
CURRENT_VERSION = "2.0.11"
# 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.
- config.gem "authlogic", :version => "2.1.5"
+ config.gem "authlogic", :version => "2.1.6"
config.gem "fastercsv", :version => "1.5.3"
config.gem "factory_girl", :version => "1.3.1"
config.gem "webrat", :version => "0.7.1"
- config.gem "haml", :version => "3.0.13"
+ config.gem "haml", :version => "3.0.18"
# 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 = :sv
# 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 = {
:key => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 2b6b78d..17674a6 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,216 +1,216 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The club will be deleted.
Are_you_sure_archive: Are you sure? The student will be archived, and thus hidden from view until unarchived.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
- Matched_x_students: Matched {{count}} students
+ Matched_x_students: Matched %{count} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
Welcome_Text: Welcome Text
Welcome_Text_descr: "This is the text that is sent in the welcome email. Use the placeholders %club%, %url% and %password% to denote the current club, URL to log in at and the user's password.."
Archive: Archive
Archived: Archived
Unarchive: Make Active
Found: Found
No_mailing_lists: There are no mailing lists available.
Admin: Admin
activerecord:
messages:
in_future: in the future
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 55c5a28..bc3d563 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,291 +1,291 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_archive: Ãr du säker? Eleven kommer att arkiveras, och därmed vara dold tills han/hon aktiveras igen.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
- Matched_x_students: Hittade {{count}} tränande
+ Matched_x_students: Hittade %{count} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
Body_text: Brödtext
Send: Skicka
Subject: Ãrende
From: Från
Back: Tillbaka
Message_sent_to: Meddelandet skickades till
Couldnt_send_to: Kunde inte skicka meddelande till
because_no_email: eftersom de inte har en epostadress.
Welcome_Text: Välkomsttext
Welcome_Text_descr: "Detta är den text som skickas ut i välkomstbrevet. Använd platshållarna %club%, %url% och %password% för att hänvisa till den aktuella klubben, URL:en att logga in på samt användarens lösenord."
Archive: Arkivera
Archived: Arkiverade
Unarchive: Gör aktiv igen
Found: Hittade
No_mailing_lists: Det finns inga tillgängliga epostlistor.
Admin: Administrativ
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
in_future: i framtiden
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/test/webrat-1282578492.html b/test/webrat-1282578492.html
new file mode 100644
index 0000000..fbc5139
--- /dev/null
+++ b/test/webrat-1282578492.html
@@ -0,0 +1,196 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>Action Controller: Exception caught</title>
+ <style>
+ body { background-color: #fff; color: #333; }
+
+ body, p, ol, ul, td {
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px;
+ }
+
+ pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px;
+ }
+
+ a { color: #000; }
+ a:visited { color: #666; }
+ a:hover { color: #fff; background-color:#000; }
+ </style>
+</head>
+<body>
+
+<h1>
+ Errno::ENOENT
+
+ in ApplicationController#edit_site_settings
+
+</h1>
+<pre>No such file or directory - public/stylesheets/themes</pre>
+
+
+
+<p><code>RAILS_ROOT: /Users/jb/Projects/GitHub/Register</code></p>
+
+<div id="traces">
+
+
+ <a href="#" onclick="document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Application-Trace').style.display='block';; return false;">Application Trace</a> |
+
+
+ <a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='block';; return false;">Framework Trace</a> |
+
+
+ <a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='block';; return false;">Full Trace</a>
+
+
+
+ <div id="Application-Trace" style="display: block;">
+ <pre><code>/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `open'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `entries'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `edit_site_settings'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `perform_action_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:617:in `call_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:160:in `perform_action_without_flash'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/flash.rb:146:in `perform_action'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `process_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:606:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:391:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:386:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:437:in `call'</code></pre>
+ </div>
+
+ <div id="Framework-Trace" style="display: none;">
+ <pre><code>/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:308:in `realtime'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:87:in `dispatch'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:121:in `_call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:130:in `build_middleware_stack'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:106:in `call'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb:46:in `run_suite'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:67:in `start_mediator'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:41:in `start'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278</code></pre>
+ </div>
+
+ <div id="Full-Trace" style="display: none;">
+ <pre><code>/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `open'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `entries'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `edit_site_settings'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `perform_action_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:617:in `call_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:308:in `realtime'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:160:in `perform_action_without_flash'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/flash.rb:146:in `perform_action'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `process_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:606:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:391:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:386:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:437:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:87:in `dispatch'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:121:in `_call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:130:in `build_middleware_stack'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:9:in `cache'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:28:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:361:in `call'
+/Library/Ruby/Gems/1.8/gems/haml-3.0.13/lib/sass/plugin/rack.rb:41:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/string_coercion.rb:25:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/head.rb:9:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/methodoverride.rb:24:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/params_parser.rb:15:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/session/cookie_store.rb:93:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/failsafe.rb:26:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `synchronize'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:106:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lint.rb:47:in `_call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lint.rb:35:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:316:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:197:in `get'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:499:in `__send__'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:499:in `get'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:50:in `send'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:50:in `do_request'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:15:in `get'
+(__FORWARDABLE__):3:in `__send__'
+(__FORWARDABLE__):3:in `get'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:280:in `send'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:280:in `process_request'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:119:in `request_page'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/elements/link.rb:20:in `click'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/scope.rb:276:in `click_link'
+(__FORWARDABLE__):3:in `__send__'
+(__FORWARDABLE__):3:in `click_link'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/methods.rb:7:in `click_link'
+integration/sitesettings_test.rb:22:in `test_set_site_theme'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/testing/setup_and_teardown.rb:62:in `__send__'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/testing/setup_and_teardown.rb:62:in `run'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:657:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb:46:in `run_suite'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:67:in `start_mediator'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:41:in `start'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
+integration/sitesettings_test.rb:38</code></pre>
+ </div>
+
+</div>
+
+
+
+
+
+
+<h2 style="margin-top: 30px">Request</h2>
+<p><b>Parameters</b>: <pre>None</pre></p>
+
+<p><a href="#" onclick="document.getElementById('session_dump').style.display='block'; return false;">Show session dump</a></p>
+<div id="session_dump" style="display:none"><pre class='debug_dump'>---
+</pre></div>
+
+
+<h2 style="margin-top: 30px">Response</h2>
+<p><b>Headers</b>: <pre>{"Content-Type"=>"",
+ "Cache-Control"=>"no-cache"}</pre></p>
+
+
+
+</body>
+</html>
\ No newline at end of file
diff --git a/test/webrat-1282578493.html b/test/webrat-1282578493.html
new file mode 100644
index 0000000..e90d64f
--- /dev/null
+++ b/test/webrat-1282578493.html
@@ -0,0 +1,196 @@
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <title>Action Controller: Exception caught</title>
+ <style>
+ body { background-color: #fff; color: #333; }
+
+ body, p, ol, ul, td {
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px;
+ }
+
+ pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px;
+ }
+
+ a { color: #000; }
+ a:visited { color: #666; }
+ a:hover { color: #fff; background-color:#000; }
+ </style>
+</head>
+<body>
+
+<h1>
+ Errno::ENOENT
+
+ in ApplicationController#edit_site_settings
+
+</h1>
+<pre>No such file or directory - public/stylesheets/themes</pre>
+
+
+
+<p><code>RAILS_ROOT: /Users/jb/Projects/GitHub/Register</code></p>
+
+<div id="traces">
+
+
+ <a href="#" onclick="document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Application-Trace').style.display='block';; return false;">Application Trace</a> |
+
+
+ <a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Full-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='block';; return false;">Framework Trace</a> |
+
+
+ <a href="#" onclick="document.getElementById('Application-Trace').style.display='none';document.getElementById('Framework-Trace').style.display='none';document.getElementById('Full-Trace').style.display='block';; return false;">Full Trace</a>
+
+
+
+ <div id="Application-Trace" style="display: block;">
+ <pre><code>/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `open'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `entries'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `edit_site_settings'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `perform_action_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:617:in `call_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:160:in `perform_action_without_flash'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/flash.rb:146:in `perform_action'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `process_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:606:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:391:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:386:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:437:in `call'</code></pre>
+ </div>
+
+ <div id="Framework-Trace" style="display: none;">
+ <pre><code>/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:308:in `realtime'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:87:in `dispatch'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:121:in `_call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:130:in `build_middleware_stack'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:106:in `call'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb:46:in `run_suite'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:67:in `start_mediator'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:41:in `start'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278</code></pre>
+ </div>
+
+ <div id="Full-Trace" style="display: none;">
+ <pre><code>/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `open'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `entries'
+/Users/jb/Projects/GitHub/Register/app/controllers/application_controller.rb:10:in `edit_site_settings'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:1331:in `perform_action_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:617:in `call_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:610:in `perform_action_without_benchmark'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:308:in `realtime'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/core_ext/benchmark.rb:17:in `ms'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:160:in `perform_action_without_flash'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/flash.rb:146:in `perform_action'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `send'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:532:in `process_without_filters'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/filters.rb:606:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:391:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/base.rb:386:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/routing/route_set.rb:437:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:87:in `dispatch'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:121:in `_call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:130:in `build_middleware_stack'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:29:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/query_cache.rb:34:in `cache'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:9:in `cache'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/query_cache.rb:28:in `call'
+/Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/connection_adapters/abstract/connection_pool.rb:361:in `call'
+/Library/Ruby/Gems/1.8/gems/haml-3.0.13/lib/sass/plugin/rack.rb:41:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/string_coercion.rb:25:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/head.rb:9:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/methodoverride.rb:24:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/params_parser.rb:15:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/session/cookie_store.rb:93:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/failsafe.rb:26:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `synchronize'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lock.rb:11:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/dispatcher.rb:106:in `call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lint.rb:47:in `_call'
+/Library/Ruby/Gems/1.8/gems/rack-1.0.1/lib/rack/lint.rb:35:in `call'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:316:in `process'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:197:in `get'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:499:in `__send__'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:499:in `get'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:50:in `send'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:50:in `do_request'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/adapters/rails.rb:15:in `get'
+(__FORWARDABLE__):3:in `__send__'
+(__FORWARDABLE__):3:in `get'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:280:in `send'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:280:in `process_request'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/session.rb:119:in `request_page'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/elements/link.rb:20:in `click'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/scope.rb:276:in `click_link'
+(__FORWARDABLE__):3:in `__send__'
+(__FORWARDABLE__):3:in `click_link'
+/Library/Ruby/Gems/1.8/gems/webrat-0.7.1/lib/webrat/core/methods.rb:7:in `click_link'
+integration/sitesettings_test.rb:40:in `test_set_site_welcome_to_blank'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/testing/setup_and_teardown.rb:62:in `__send__'
+/Library/Ruby/Gems/1.8/gems/activesupport-2.3.5/lib/active_support/testing/setup_and_teardown.rb:62:in `run'
+/Library/Ruby/Gems/1.8/gems/actionpack-2.3.5/lib/action_controller/integration.rb:657:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:34:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `each'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/testsuite.rb:33:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnermediator.rb:46:in `run_suite'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:67:in `start_mediator'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/console/testrunner.rb:41:in `start'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/ui/testrunnerutilities.rb:29:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
+/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/test/unit.rb:278
+integration/sitesettings_test.rb:38</code></pre>
+ </div>
+
+</div>
+
+
+
+
+
+
+<h2 style="margin-top: 30px">Request</h2>
+<p><b>Parameters</b>: <pre>None</pre></p>
+
+<p><a href="#" onclick="document.getElementById('session_dump').style.display='block'; return false;">Show session dump</a></p>
+<div id="session_dump" style="display:none"><pre class='debug_dump'>---
+</pre></div>
+
+
+<h2 style="margin-top: 30px">Response</h2>
+<p><b>Headers</b>: <pre>{"Content-Type"=>"",
+ "Cache-Control"=>"no-cache"}</pre></p>
+
+
+
+</body>
+</html>
\ No newline at end of file
|
calmh/Register
|
2b49aea4d86758d26d9f5a966d6d2cf51f1a50bc
|
Birth date must be a valid date
|
diff --git a/test/unit/student_test.rb b/test/unit/student_test.rb
index f9c4bd6..ac3d13d 100644
--- a/test/unit/student_test.rb
+++ b/test/unit/student_test.rb
@@ -1,135 +1,140 @@
require 'test_helper'
class StudentTest < ActiveSupport::TestCase
def setup
Factory(:student, :personal_number => '19710730-3187')
@student = Factory(:student)
end
test "luhn calculation valid" do
@student.personal_number = "198002020710"
assert @student.luhn == 0
end
test "luhn calculation invalid" do
@student.personal_number = "198102020710"
assert @student.luhn != 0
end
test "personal number must be unique" do
@student.personal_number = "19710730-3187"
assert [email protected]?
end
test "autocorrection should do nothing with clearly invalid format" do
@student.personal_number = "abc123"
assert @student.personal_number == "abc123"
end
test "autocorrection should pass on correct format but unreasonable date" do
@student.personal_number = "20710730-3187"
assert @student.personal_number == "20710730-3187"
end
test "autocorrection should add century and dash" do
@student.personal_number = "7107303187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrection should add century" do
@student.personal_number = "710730-3187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrectionion should add dash" do
@student.personal_number = "197107303187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrect should pass correct personal number" do
@student.personal_number = "19710730-3187"
assert @student.personal_number == "19710730-3187"
end
test "personal number must follow correct format" do
@student.personal_number = "abc123"
assert [email protected]?
end
test "personal number must not be too far in the future" do
@student.personal_number = "20550213-2490"
assert [email protected]?
end
+ test "birth date must be a valid date" do
+ @student.personal_number = "19929593"
+ assert [email protected]?
+ end
+
if REQUIRE_PERSONAL_NUMBER
test "personal number cannot be nil" do
@student.personal_number = nil
assert [email protected]?
end
test "personal number must not be blank" do
@student.personal_number = ""
assert [email protected]?
end
test "century digits will be auto added" do
@student.personal_number = "550213-2490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "century digits and dash will be auto added" do
@student.personal_number = "5502132490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "dash will be auto added" do
@student.personal_number = "195502132490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "valid personal number should be accepted" do
@student.personal_number = "19550213-2490"
assert @student.valid?
end
if BIRTHDATE_IS_ENOUGH
test "valid birth date should be accepted" do
@student.personal_number = "19550213"
assert @student.valid?
end
else
test "only birth date should not be accepted" do
@student.personal_number = "19550213"
assert [email protected]?
end
end
end
test "gender should be set manually in lack of personal number" do
@student.personal_number = nil
@student.gender = "male"
assert @student.gender == "male"
@student.gender = "female"
assert @student.gender == "female"
end
test "gender should be set from personal number, male" do
@student.personal_number = "19550213-2490"
@student.gender = "female"
assert @student.gender == "male"
end
test "gender should be set from personal number, female" do
@student.personal_number = "19680614-5527"
@student.gender = "male"
assert @student.gender == "female"
end
test "current grade should be nil by default" do
assert @student.current_grade == nil
end
end
|
calmh/Register
|
8ed1a628f0506bdbfa2cdc258a34dd9edd8b4427
|
Blank site settings are valid.
|
diff --git a/app/models/configuration_setting.rb b/app/models/configuration_setting.rb
index 44d3e57..15c5738 100644
--- a/app/models/configuration_setting.rb
+++ b/app/models/configuration_setting.rb
@@ -1,4 +1,4 @@
class ConfigurationSetting < ActiveRecord::Base
- validates_presence_of :setting, :value
+ validates_presence_of :setting
validates_uniqueness_of :setting
end
diff --git a/test/integration/sitesettings_test.rb b/test/integration/sitesettings_test.rb
index b139116..53da973 100644
--- a/test/integration/sitesettings_test.rb
+++ b/test/integration/sitesettings_test.rb
@@ -1,37 +1,45 @@
require 'test_helper'
class SiteSettingsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
Factory(:configuration_setting, :setting => :site_name, :value => 'The site')
Factory(:configuration_setting, :setting => :welcome_text, :value => 'Welcome text')
end
test "set site name" do
log_in_as_admin
click_link "Site settings"
fill_in "Site name", :with => "New site name"
click_button "Save"
click_link "Clubs"
assert_contain "New site name"
assert_not_contain "The site"
end
test "set site theme" do
log_in_as_admin
click_link "Site settings"
select "orange"
click_button "Save"
click_link "Clubs"
#assert_contain "orange/style.css"
end
test "set site welcome" do
log_in_as_admin
click_link "Site settings"
fill_in "Welcome Text", :with => "New welcome text"
click_button "Save"
click_link "Site settings"
assert_contain "New welcome text"
end
+
+ test "set site welcome to blank" do
+ log_in_as_admin
+ click_link "Site settings"
+ fill_in "Welcome Text", :with => ""
+ click_button "Save"
+ assert_contain "settings were updated"
+ end
end
|
calmh/Register
|
252ef9ee8df9bf5fcf92cfb60b073fe01ba7ba9f
|
Bump version number to 2.0.11.
|
diff --git a/config/environment.rb b/config/environment.rb
index 537b2fb..57fb194 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,95 +1,95 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
-CURRENT_VERSION = "2.0.10"
+CURRENT_VERSION = "2.0.11"
# 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.
config.gem "authlogic", :version => "2.1.5"
config.gem "fastercsv", :version => "1.5.3"
config.gem "factory_girl", :version => "1.3.1"
config.gem "webrat", :version => "0.7.1"
config.gem "haml", :version => "3.0.13"
# 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 = :sv
# 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 = {
:key => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
0e8d05eff8d543b76beb888d93907e3ea582766e
|
Revert to Rails 2.3.5 that doesn't break tests, update to newer gem versions.
|
diff --git a/config/environment.rb b/config/environment.rb
index 8d87f48..537b2fb 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,99 +1,95 @@
# 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.3.8' unless defined? RAILS_GEM_VERSION
+RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
CURRENT_VERSION = "2.0.10"
# 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 "authlogic", :version => "2.1.3"
- config.gem "fastercsv"
- config.gem "factory_girl"
+ config.gem "authlogic", :version => "2.1.5"
+ config.gem "fastercsv", :version => "1.5.3"
+ config.gem "factory_girl", :version => "1.3.1"
+ config.gem "webrat", :version => "0.7.1"
+ config.gem "haml", :version => "3.0.13"
# 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 = :sv
# 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 = {
:key => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
9bee4afef2f66e95f98dd2e972cb8b7e803e641d
|
Reformatting.
|
diff --git a/config/boot.rb b/config/boot.rb
index 035fc52..dd5e3b6 100644
--- a/config/boot.rb
+++ b/config/boot.rb
@@ -1,110 +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
min_version = '1.3.2'
require 'rubygems'
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
+ def read_environment_rb
+ File.read("#{RAILS_ROOT}/config/environment.rb")
+ end
end
end
end
# All that for this:
Rails.boot!
|
calmh/Register
|
edbabb030638abf56a2458185357252b5b613c5f
|
Rails 2.3.8 compatibility
|
diff --git a/config/environment.rb b/config/environment.rb
index dcad6dc..8d87f48 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,99 +1,99 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
+RAILS_GEM_VERSION = '2.3.8' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
CURRENT_VERSION = "2.0.10"
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
+ :key => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
66adc5ea39ceef2492078f29df5c466322a6992a
|
Bump version number to 2.0.10.
|
diff --git a/config/environment.rb b/config/environment.rb
index 2c76fe6..dcad6dc 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,99 +1,99 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
-CURRENT_VERSION = "2.0.9"
+CURRENT_VERSION = "2.0.10"
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
a15a0c5767bd33d3b4ea86f53b871f50c5ea8941
|
Plugin update.
|
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb
index f9fdfdc..3b64a9e 100644
--- a/vendor/plugins/haml/init.rb
+++ b/vendor/plugins/haml/init.rb
@@ -1,16 +1,18 @@
begin
require File.join(File.dirname(__FILE__), 'lib', 'haml') # From here
rescue LoadError
begin
require 'haml' # From gem
rescue LoadError => e
# gems:install may be run to install Haml with the skeleton plugin
# but not the gem itself installed.
# Don't die if this is the case.
- raise e unless defined?(Rake) && Rake.application.top_level_tasks.include?('gems:install')
+ raise e unless defined?(Rake) &&
+ (Rake.application.top_level_tasks.include?('gems') ||
+ Rake.application.top_level_tasks.include?('gems:install'))
end
end
# Load Haml and Sass.
# Haml may be undefined if we're running gems:install.
Haml.init_rails(binding) if defined?(Haml)
|
calmh/Register
|
e280d54a82f48ce6e99ee0e9a995b63aa231f25f
|
Remove duplicate definition.
|
diff --git a/test/factories.rb b/test/factories.rb
index de2343f..79d6b2c 100644
--- a/test/factories.rb
+++ b/test/factories.rb
@@ -1,146 +1,141 @@
def cached_association(key)
object = key.to_s.camelize.constantize.first
object ||= Factory(key)
end
Factory.sequence :pnumber do |n|
last = n % 1000; n /= 1000
day = (n % 28) + 1; n /= 28
month = (n % 12) + 1; n /= 12
year = 1980 + n
personal_number = "%4d%02d%02d-%03d"%[year, month, day, last]
# Calculate valid check digit
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..13].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
check = (10 - sum) % 10
personal_number + check.to_s
end
Factory.define :grade_category do |c|
c.sequence(:category) { |n| "Category #{n}" }
end
Factory.define :grade do |c|
c.sequence(:level) { |n| n }
c.description { |g| "Grade #{g.level}" }
end
Factory.define :graduation do |f|
f.instructor "Instructor"
f.examiner "Examiner"
f.graduated Time.now
f.grade { cached_association(:grade) }
f.grade_category { cached_association(:grade_category) }
f.student { cached_association(:grade) }
end
Factory.define :group do |f|
f.sequence(:identifier) { |n| "Group #{n}" }
f.comments "An auto-created group"
f.default 0
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :mailing_list do |f|
f.sequence(:email) { |n| "list#{n}@example.com" }
f.sequence(:description) { |n| "Mailing List #{n}" }
f.security "public"
f.default 0
end
Factory.define :mailing_lists_students do |f|
f.association :mailing_list
f.association :student
end
-Factory.define :groups_students do |f|
- f.association :group
- f.association :student
-end
-
Factory.define :club do |c|
c.sequence(:name) {|n| "Club #{n}" }
end
Factory.define :board_position do |c|
c.position "Secretary"
end
Factory.define :club_position do |c|
c.position "Instructor"
end
Factory.define :title do |c|
c.title "Student"
c.level 1
end
Factory.define :payment do |c|
c.amount 700
c.received Time.now
c.description "Comment"
end
Factory.define :student do |s|
s.fname 'John'
s.sequence(:sname) {|n| "Doe_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) { |n| "person#{n}@example.com" }
s.personal_number { Factory.next(:pnumber) }
s.main_interest { cached_association(:grade_category) }
s.club { cached_association(:club) }
s.club_position { cached_association(:club_position) }
s.board_position { cached_association(:board_position) }
s.title { cached_association(:title) }
s.archived 0
end
Factory.define :administrator do |s|
s.fname 'Admin'
s.sequence(:sname) {|n| "Istrator_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "admin#{n}@example.com" }
s.sequence(:login) {|n| "admin#{n}" }
s.clubs_permission true
s.users_permission true
s.groups_permission true
s.mailinglists_permission true
s.site_permission true
end
Factory.define :club_admin, :class => 'administrator' do |s|
s.fname 'Club'
s.sequence(:sname) {|n| "Admin_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "club_admin#{n}@example.com" }
s.sequence(:login) {|n| "club_admin#{n}" }
s.clubs_permission false
s.users_permission false
s.groups_permission false
s.mailinglists_permission false
s.site_permission false
end
Factory.define :permission do |p|
p.association :club
p.association :user, :factory => :administrator
p.permission "read"
end
Factory.define :configuration_setting do |o|
o.setting "setting"
o.value "value"
end
|
calmh/Register
|
ff3629ff938f849a27c39197359b95ca7733b378
|
Bump version number to 2.0.9.
|
diff --git a/config/environment.rb b/config/environment.rb
index 827c81d..2c76fe6 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,99 +1,99 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# Version string
-CURRENT_VERSION = "2.0.8"
+CURRENT_VERSION = "2.0.9"
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
e517e4071c0f46daf7263f40455a8d737d189a27
|
Ignore .DS_Store files.
|
diff --git a/.gitignore b/.gitignore
index d021f82..95fde47 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,9 +1,9 @@
db/*.sqlite3
log/*.log
tmp/**/*
tmp/*
doc/api
doc/app
public/stylesheets/web_app_theme_override.css
.sass-cache
-
+.DS_Store
|
calmh/Register
|
6c68c5765807fcbcf8eeac0ea8bb453a63fc0f39
|
Release tagging script.
|
diff --git a/bin/make-release b/bin/make-release
new file mode 100755
index 0000000..4c3b9fa
--- /dev/null
+++ b/bin/make-release
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+export VER=$1
+
+git checkout -b release-$VER
+sed "s/CURRENT_VERSION = \".*\"/CURRENT_VERSION = \"$VER\"/" < config/environment.rb > config/environment.rb.new || exit -1
+mv config/environment.rb.new config/environment.rb
+git commit -am "Bump version number to $VER."
+
+git checkout master
+git merge --no-ff release-$VER
+git tag -a v$VER -m "Release $VER"
+
+git checkout develop
+git merge release-$VER
+git branch -d release-$VER
+
|
calmh/Register
|
4e7e8ad9e7a655d51c591c16c87bf4e2a879772d
|
Static version variable.
|
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 59dc91d..80496e0 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,61 +1,57 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def get_config(setting)
SiteSettings.get_setting(setting)
end
def grades
Grade.find(:all, :order => :level)
end
def grade_categories
GradeCategory.find(:all, :order => :category)
end
def titles
Title.find(:all, :order => :level)
end
def board_positions
BoardPosition.find(:all, :order => :id)
end
def club_positions
ClubPosition.find(:all, :order => :id)
end
def grade_str(graduation)
if graduation == nil
return "-"
else
return graduation.grade.description + " (" + graduation.grade_category.category + ")"
end
end
def groups
Group.find(:all, :order => :identifier)
end
def clubs
Club.find(:all, :order => :name)
end
def mailing_lists
MailingList.find(:all, :order => :description)
end
- def version
- `git describe`.strip.sub(/-(\d+)-g[0-9a-f]+$/, '+\1')
- end
-
def active_string(active)
return 'active' if active
''
end
def sort_link(title, column, options = {})
condition = options[:unless] if options.has_key?(:unless)
sort_dir = params[:d] == 'up' ? 'down' : 'up'
link_to_unless condition, title, request.parameters.merge( {:c => column, :d => sort_dir} )
end
end
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 3b8cbf5..2036d07 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,51 +1,51 @@
!!!
%html
- cache('layout_header') do
%head
%title= get_config(:site_name)
= stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style"
= stylesheet_link_tag 'web_app_theme_override'
%body
#container
#header
%h1
%a{ :href => root_path }= get_config(:site_name)
#user-navigation
%ul
- if current_user
- if current_user.type == 'Administrator'
%li= link_to t(:Profile), administrator_path(current_user)
%li=link_to t(:Logout), user_session_path, :method => :delete, :class => "logout"
- for locale in I18n.available_locales do
- if locale.to_s != I18n.locale.to_s
%li= link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s
.clear
- if ! ['user_sessions', 'password_resets'].include?(controller.controller_name)
#main-navigation
%ul
= render :partial => 'application/links'
.clear
#wrapper
.flash
- flash.each do |type, message|
%div{ :class => "message " + type.to_s }
%p= message
#main
= yield
- cache('layout_footer') do
#footer
.block
%p
- #{t(:Register)} v#{version}
+ #{t(:Register)} v#{CURRENT_VERSION}
 | 
#{COPYRIGHT}
 | 
= link_to t(:Report_bug), 'http://github.com/calmh/Register/issues'
 | 
= link_to t(:View_source), 'http://github.com/calmh/Register'
#sidebar= yield :sidebar
.clear
diff --git a/config/environment.rb b/config/environment.rb
index d221eb0..827c81d 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,97 +1,99 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
+# Version string
+CURRENT_VERSION = "2.0.8"
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
87210aa02892dc05766a8955aed6748ec0e882d3
|
Introduce admin-only lists and improve mailing list updating
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index e3606f3..b6a5b6a 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,332 +1,338 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = [ "archived = 0" ]
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def archive
@student = Student.find(params[:id])
@student.archived = 1
@student.save
redirect_to(@student.club)
end
def unarchive
@student = Student.find(params[:id])
@student.archived = 0
@student.save
redirect_to archived_club_students_path(@student.club)
end
def archived
@club = Club.find(params[:club_id])
@students = @club.students.archived
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
- # You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to].keys
- if !current_user.kind_of? Administrator
- cur_ids = @student.mailing_list_ids
- ml_ids = ml_ids.select do |x|
- if cur_ids.include?(x)
- true
- next
- end
- ml = MailingList.find(x)
- ml.security == 'public' && ( ml.club == nil || ml.club == @club )
+ cur_ids = @student.mailing_list_ids
+
+ cur_ids.each do |list_id|
+ if !ml_ids.include? list_id
+ ml = MailingList.find(list_id)
+ @student.mailing_lists.delete(ml)
+ end
+ end
+
+ ml_ids.each do |list_id|
+ next if cur_ids.include? list_id
+ ml = MailingList.find(list_id)
+ if ( ml.club == nil || ml.club == @club ) &&
+ ( ml.security == 'public' ||
+ ( ml.security == 'private' && current_user.edit_club_permission?(@club) ) ||
+ ( ml.security == 'admin' && current_user.mailinglists_permission? ) )
+ @student.mailing_lists << ml
end
end
- @student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
diff --git a/app/views/mailing_lists/_form.html.haml b/app/views/mailing_lists/_form.html.haml
index 17f38be..126ccea 100644
--- a/app/views/mailing_lists/_form.html.haml
+++ b/app/views/mailing_lists/_form.html.haml
@@ -1,46 +1,46 @@
.group
= f.label :email, t(:Email), :class => :label
= f.text_field :email, :class => 'text_field'
.group
= f.label :description, t(:Description), :class => :label
= f.text_field :description, :class => 'text_field'
.group
= f.label :security, t(:Security), :class => :label
- = f.select(:security, { t(:Public) => 'public', t(:Private) => 'private' })
+ = f.select(:security, { t(:Public) => 'public', t(:Private) => 'private', t(:Admin) => 'admin' })
%br
%span.description= t(:Security_descr)
.group
= f.label :club, t(:Club), :class => :label
= f.select(:club_id, [ [ t(:None), nil ] ] + clubs.map { |c| [c.name, c.id ]})
.group
= f.label :default, t(:Default), :class => :label
= f.check_box :default
%br
%span.description= t(:Default_ML_descr)
- if controller.action_name != "new"
.group
= f.label nil, t(:Members), :class => :label
- @students = @mailing_list.students
%table.table
%tr
%th.first= t(:Club)
%th= t(:Groups)
%th.last= t(:Name)
- @students.each do |student|
%tr{ :class => cycle("odd", "even") }
%td= link_to student.club.name, club_path(student.club)
%td= student.groups.map{ |g| g.identifier }.join(", ")
%td= link_to student.name, student_path(student)
.group.navform
%input.button{ :type => "submit", :value => t(:Save) + " →" }
- if controller.action_name != "new"
= t(:or)
= link_to t(:Destroy), @mailing_list, :confirm => t(:Are_you_sure_mailing_list), :method => :delete
= t(:or)
= link_to t(:Cancel), mailing_lists_path
diff --git a/app/views/students/_form.html.haml b/app/views/students/_form.html.haml
index f2e8d02..83db760 100644
--- a/app/views/students/_form.html.haml
+++ b/app/views/students/_form.html.haml
@@ -1,105 +1,109 @@
= f.hidden_field :club_id, :class => 'text_field'
.group
%label.label= t(:Groups)
- groups.each do |group|
= check_box_tag "member_of[" + group.id.to_s + "]", value = "1", checked = @student.group_ids.include?(group.id), :class => 'checkbox'
%label{ :for => "member_of_" + group.id.to_s }= group.identifier
%br
.group
= f.label :fname, t(:Fname), :class => :label
= f.text_field :fname, :class => 'text_field'
.group
= f.label :sname, t(:Sname), :class => :label
= f.text_field :sname, :class => 'text_field'
.group
= f.label :personal_number, t(:Personal_Num), :class => :label
= f.text_field :personal_number, :class => 'text_field'
%span.description= t(:Personal_Num_descr)
.group
= f.label :gender, t(:Gender), :class => :label
= select "student", "gender", ['male', 'female', 'unknown'].map { |g| [ t(g).titlecase, g ] }
%br
%span.description= t(:Gender_descr)
.group
= f.label :main_interest_id, t(:Main_Interest), :class => :label
= select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] }
%br
.group
= f.label :email, t(:Email), :class => :label
= f.text_field :email, :class => 'text_field'
.group
%label.label= t(:Mailing_Lists)
+ - num_displayed_lists = 0
- mailing_lists.each do |ml|
- - if ml.club == nil || ml.club == @club
+ - if (ml.security != "admin" || current_user.mailinglists_permission?) && (ml.club == nil || ml.club == @club)
= check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id), :class => 'checkbox'
%label{ :for => "subscribes_to_" + ml.id.to_s }= ml.description
%br
+ - num_displayed_lists += 1
+ - if num_displayed_lists == 0
+ %span.description= t(:No_mailing_lists)
.group
= f.label :home_phone, t(:Home_phone), :class => :label
= f.text_field :home_phone, :class => 'text_field'
%span.description= t(:Phone_number_descr)
.group
= f.label :mobile_phone, t(:Mobile_phone), :class => :label
= f.text_field :mobile_phone, :class => 'text_field'
%span.description= t(:Phone_number_descr)
.group
= f.label :street, t(:Street), :class => :label
= f.text_field :street, :class => 'text_field'
.group
= f.label :zipcode, t(:Zipcode), :class => :label
= f.text_field :zipcode, :class => 'text_field'
.group
= f.label :city, t(:City), :class => :label
= f.text_field :city, :class => 'text_field'
.group
= f.label :title_id, t(:Title), :class => :label
= select "student", "title_id", titles.map { |g| [ g.title, g.id ] }
%br
.group
= f.label :club_position_id, t(:Club_Position), :class => :label
= select "student", "club_position_id", club_positions.map { |g| [ g.position, g.id ] }
%br
.group
= f.label :board_position_id, t(:Board_Position), :class => :label
= select "student", "board_position_id", board_positions.map { |g| [ g.position, g.id ] }
%br
.group
= f.label :comments, t(:Comments), :class => :label
= f.text_area :comments, :class => 'text_area', :rows => 4, :cols => 16
.group
= f.label :password, t(:New_Password), :class => :label
= f.password_field :password, :class => 'text_field'
%span.description= t(:New_Password_descr)
.group
= f.label :password_confirmation, t(:Confirm_Password), :class => :label
= f.password_field :password_confirmation, :class => 'text_field'
.group.navform
%input.button{ :type => 'submit', :value => t(:Save) + " →" }
- if controller.action_name != "new" && controller.action_name != "create"
= t(:or)
= link_to t(:Archive), archive_student_path(@student), :confirm => t(:Are_you_sure_archive)
- if current_user.delete_permission?(@club)
= t(:or)
= link_to t(:Destroy), @student, :confirm => t(:Are_you_sure_student), :method => :delete
= t(:or)
= link_to t(:Cancel), student_path(@student)
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 1ce0dbf..2b6b78d 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,214 +1,216 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The club will be deleted.
Are_you_sure_archive: Are you sure? The student will be archived, and thus hidden from view until unarchived.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
Welcome_Text: Welcome Text
Welcome_Text_descr: "This is the text that is sent in the welcome email. Use the placeholders %club%, %url% and %password% to denote the current club, URL to log in at and the user's password.."
Archive: Archive
Archived: Archived
Unarchive: Make Active
Found: Found
+ No_mailing_lists: There are no mailing lists available.
+ Admin: Admin
activerecord:
messages:
in_future: in the future
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 05b92f0..55c5a28 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,289 +1,291 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_archive: Ãr du säker? Eleven kommer att arkiveras, och därmed vara dold tills han/hon aktiveras igen.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
Body_text: Brödtext
Send: Skicka
Subject: Ãrende
From: Från
Back: Tillbaka
Message_sent_to: Meddelandet skickades till
Couldnt_send_to: Kunde inte skicka meddelande till
because_no_email: eftersom de inte har en epostadress.
Welcome_Text: Välkomsttext
Welcome_Text_descr: "Detta är den text som skickas ut i välkomstbrevet. Använd platshållarna %club%, %url% och %password% för att hänvisa till den aktuella klubben, URL:en att logga in på samt användarens lösenord."
Archive: Arkivera
Archived: Arkiverade
Unarchive: Gör aktiv igen
Found: Hittade
+ No_mailing_lists: Det finns inga tillgängliga epostlistor.
+ Admin: Administrativ
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
in_future: i framtiden
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/test/integration/mailing_list_test.rb b/test/integration/mailing_list_test.rb
index 76eafe5..849e352 100644
--- a/test/integration/mailing_list_test.rb
+++ b/test/integration/mailing_list_test.rb
@@ -1,170 +1,222 @@
require 'test_helper'
class MailingListTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@admin.mailinglists_permission = true
@admin.save
- @mailing_lists = []
- @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Zz List")
- @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Bb List")
- @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Cc List")
- @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Aa List")
+ @public_mailing_lists = []
+ @public_mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Zz List", :security => "public")
+ @public_mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Aa List", :security => "private")
+ @admin_mailing_lists = []
+ @admin_mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Bb List", :security => "admin")
+ @admin_mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Cc List", :security => "admin")
+ @mailing_lists = @public_mailing_lists + @admin_mailing_lists
@students = 5.times.map { Factory(:student) }
@unsorted_students = [ Factory(:student, :fname => "Bb", :sname => "Bb"),
Factory(:student, :fname => "Aa", :sname => "Aa"),
Factory(:student, :fname => "Zz", :sname => "Zz") ]
@member_list = @mailing_lists[0]
@students.each do |s|
s.mailing_lists << @member_list
s.save
end
end
test "mailing lists should be displayed on the list page" do
log_in_as_admin
click_link "Mailing lists"
@mailing_lists.each do |m|
assert_contain m.email
assert_contain m.description
end
end
test "mailing lists should be displayed on the list page, and should be sorted by email" do
log_in_as_admin
click_link "Mailing lists"
assert_contain /aa@example.*bb@example.*cc@example.*zz@example/m
end
test "should create new mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => "[email protected]"
fill_in "Description", :with => "A test list"
- fill_in "Security", :with => "public"
+ select "Public"
+
+ click_button "Save"
+ click_link "Mailing lists"
+
+ assert_contain "[email protected]"
+ assert_contain "A test list"
+ end
+
+ test "should create new mailing list with admin security" do
+ log_in_as_admin
+
+ click_link "Mailing lists"
+ click_link "New mailing list"
+
+ fill_in "Email", :with => "[email protected]"
+ fill_in "Description", :with => "A test list"
+ select "Admin"
click_button "Save"
click_link "Mailing lists"
assert_contain "[email protected]"
assert_contain "A test list"
end
test "should delete a mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link @mailing_lists[0].email
click_link "Destroy"
click_link "Mailing lists"
assert_not_contain @mailing_lists[0].email
end
test "should not be able to create a new mailing list with non-unique email" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => @mailing_lists[0].email
fill_in "Description", :with => "A test list"
fill_in "Security", :with => "public"
click_button "Save"
assert_contain "taken"
end
test "mailing list should show members" do
log_in_as_admin
click_link "Mailing lists"
click_link @member_list.email
@students.each do |s|
assert_contain s.name
end
end
test "mailing list should display students sorted by name, even if added randomly" do
log_in_as_admin
@unsorted_students.each do |student|
click_link @club.name
click_link student.name
click_link "Edit"
check @mailing_lists[2].description
click_button "Save"
end
click_link "Mailing lists"
click_link @mailing_lists[2].email
assert_contain /Aa Aa.*Bb Bb.*Zz Zz/m
end
test "remove student from mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
assert_not_contain @member_list.description
end
test "remove student from mailing list, and verify this on the membership page" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
click_link "Mailing lists"
click_link @member_list.email
assert_not_contain @students[0].name
end
test "add student to one mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
click_button "Save"
assert_contain @mailing_lists[1].description
end
test "add student to two mailing lists" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
check @mailing_lists[2].description
click_button "Save"
assert_contain @mailing_lists[1].description
assert_contain @mailing_lists[2].description
end
+
+ test "club admin should not see mailing lists with admin security" do
+ log_in_as_club_admin
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
+
+ @public_mailing_lists.each do |m|
+ assert_contain m.description
+ end
+ @admin_mailing_lists.each do |m|
+ assert_not_contain m.description
+ end
+
+ assert_not_contain "no mailing lists"
+ end
+
+ test "club admin should see 'no mailing lists' when there are only admin lists available" do
+ log_in_as_club_admin
+ @public_mailing_lists.each do |m|
+ m.destroy
+ end
+
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
+
+ @admin_mailing_lists.each do |m|
+ assert_not_contain m.description
+ end
+
+ assert_contain "There are no mailing lists available."
+ end
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index bab9dca..95a9a32 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,293 +1,312 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
test "student page should show all students" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should show only this club's students" do
other_club = Factory(:club)
other_students = 10.times.map { Factory(:student, :club => other_club )}
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
other_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
archived_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "archived page should display only archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "Archived"
@students.each do |s|
assert_not_contain Regexp.new("\\b" + s.name + "\\b")
end
archived_students.each do |s|
assert_contain Regexp.new("\\b" + s.name + "\\b")
end
end
test "unarchive student should remove him/her from archived page" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "Archived"
visit "/students/#{archived_students[0].id}/unarchive"
assert_not_contain Regexp.new("\\b" + archived_students[0].name + "\\b")
archived_students.delete_at 0
archived_students.each do |s|
assert_contain Regexp.new("\\b" + s.name + "\\b")
end
end
test "overview page student count should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
assert_contain Regexp.new("\\b#{@students.length}\\b")
assert_not_contain Regexp.new("\\b#{@students.length + archived_students.length}\\b")
end
test "student should be archived and then not be listed on the club page" do
archived = @students[0]
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link archived.name
click_link "Edit"
click_link "Archive"
click_link @club.name
assert_not_contain archived.name
end
test "should not create new blank student" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
click_button "Save"
assert_not_contain "created"
assert_contain "can't be blank"
end
test "should create new student with minimal info" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
select @category.category
click_button "Save"
assert_contain "created"
end
test "should create a new student in x groups" do
@admin.groups_permission = true
@admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_groups.each do |g|
check g.identifier
end
click_button "Save"
assert_contain "created"
member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_contain "Test Testsson"
end
non_member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_not_contain "Test Testsson"
end
end
test "should create a new student in x mailing lists" do
@admin.mailinglists_permission = true
@admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_lists.each do |m|
check m.description
end
click_button "Save"
assert_contain "created"
member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_contain "Test Testsson"
end
non_member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_not_contain "Test Testsson"
end
end
test "new student should join club mailing list per default" do
mailing_list = Factory(:mailing_list, :default => 1)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
other_club = Factory(:club)
mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_not_contain "Test Testsson"
end
test "student should be able to edit self without losing groups" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
group = Factory(:group)
student.groups << group;
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.groups.length == 1
end
test "student should join mailing list" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_list = Factory(:mailing_list)
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_list.description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == [ mailing_list.id ]
end
test "student should join one mailing list and leave another" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
end
+
+ test "student leave all mailing lists" do
+ student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
+ mailing_lists = 2.times.map { Factory(:mailing_list) }
+ student.mailing_lists << mailing_lists[1]
+ student.save!
+
+ visit "/?locale=en"
+ fill_in "Login", :with => student.email
+ fill_in "Password", :with => "password"
+ click_button "Log in"
+
+ uncheck mailing_lists[0].description
+ uncheck mailing_lists[1].description
+ click_button "Save"
+
+ student_from_db = Student.find(student.id)
+ assert student_from_db.mailing_list_ids == []
+ end
end
|
calmh/Register
|
bea0d2fb3571ab3f887573f083dfacc2b53276c7
|
Add 'club admin' factory
|
diff --git a/app/models/mailing_list.rb b/app/models/mailing_list.rb
index 6dffc77..3f7c672 100644
--- a/app/models/mailing_list.rb
+++ b/app/models/mailing_list.rb
@@ -1,7 +1,7 @@
class MailingList < ActiveRecord::Base
has_and_belongs_to_many :students, :order => "fname, sname"
belongs_to :club
- validates_format_of :security, :with => /^public|private$/
+ validates_format_of :security, :with => /^public|private|admin$/
validates_format_of :email, :with => /^[a-z_.0-9-]+@[a-z0-9.-]+/
validates_uniqueness_of :email
end
diff --git a/test/factories.rb b/test/factories.rb
index 3979427..de2343f 100644
--- a/test/factories.rb
+++ b/test/factories.rb
@@ -1,132 +1,146 @@
def cached_association(key)
object = key.to_s.camelize.constantize.first
object ||= Factory(key)
end
Factory.sequence :pnumber do |n|
last = n % 1000; n /= 1000
day = (n % 28) + 1; n /= 28
month = (n % 12) + 1; n /= 12
year = 1980 + n
personal_number = "%4d%02d%02d-%03d"%[year, month, day, last]
# Calculate valid check digit
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..13].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
check = (10 - sum) % 10
personal_number + check.to_s
end
Factory.define :grade_category do |c|
c.sequence(:category) { |n| "Category #{n}" }
end
Factory.define :grade do |c|
c.sequence(:level) { |n| n }
c.description { |g| "Grade #{g.level}" }
end
Factory.define :graduation do |f|
f.instructor "Instructor"
f.examiner "Examiner"
f.graduated Time.now
f.grade { cached_association(:grade) }
f.grade_category { cached_association(:grade_category) }
f.student { cached_association(:grade) }
end
Factory.define :group do |f|
f.sequence(:identifier) { |n| "Group #{n}" }
f.comments "An auto-created group"
f.default 0
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :mailing_list do |f|
f.sequence(:email) { |n| "list#{n}@example.com" }
f.sequence(:description) { |n| "Mailing List #{n}" }
f.security "public"
f.default 0
end
Factory.define :mailing_lists_students do |f|
f.association :mailing_list
f.association :student
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :club do |c|
c.sequence(:name) {|n| "Club #{n}" }
end
Factory.define :board_position do |c|
c.position "Secretary"
end
Factory.define :club_position do |c|
c.position "Instructor"
end
Factory.define :title do |c|
c.title "Student"
c.level 1
end
Factory.define :payment do |c|
c.amount 700
c.received Time.now
c.description "Comment"
end
Factory.define :student do |s|
s.fname 'John'
s.sequence(:sname) {|n| "Doe_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) { |n| "person#{n}@example.com" }
s.personal_number { Factory.next(:pnumber) }
s.main_interest { cached_association(:grade_category) }
s.club { cached_association(:club) }
s.club_position { cached_association(:club_position) }
s.board_position { cached_association(:board_position) }
s.title { cached_association(:title) }
s.archived 0
end
Factory.define :administrator do |s|
s.fname 'Admin'
s.sequence(:sname) {|n| "Istrator_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "admin#{n}@example.com" }
s.sequence(:login) {|n| "admin#{n}" }
s.clubs_permission true
s.users_permission true
s.groups_permission true
s.mailinglists_permission true
s.site_permission true
end
+Factory.define :club_admin, :class => 'administrator' do |s|
+ s.fname 'Club'
+ s.sequence(:sname) {|n| "Admin_#{n}" }
+ s.password "password"
+ s.password_confirmation "password"
+ s.sequence(:email) {|n| "club_admin#{n}@example.com" }
+ s.sequence(:login) {|n| "club_admin#{n}" }
+ s.clubs_permission false
+ s.users_permission false
+ s.groups_permission false
+ s.mailinglists_permission false
+ s.site_permission false
+end
+
Factory.define :permission do |p|
p.association :club
p.association :user, :factory => :administrator
p.permission "read"
end
Factory.define :configuration_setting do |o|
o.setting "setting"
o.value "value"
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index f3d9c70..0c75b26 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,42 +1,52 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'setup_once'
require 'test_help'
require "webrat"
Webrat.configure do |config|
config.mode = :rails
end
class ActiveSupport::TestCase
# setup :activate_authlogic
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
def create_club_and_admin
@club = Factory(:club)
@admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
+ @ca = Factory(:club_admin, :login => 'club_admin', :password => 'club_admin', :password_confirmation => 'club_admin')
%w[read edit delete graduations payments export].each do |perm|
Factory(:permission, :club => @club, :user => @admin, :permission => perm)
+ Factory(:permission, :club => @club, :user => @ca, :permission => perm)
end
end
def log_in_as_admin
visit "/?locale=en"
fill_in "Login", :with => "admin"
fill_in "Password", :with => "admin"
uncheck "Remember me"
click_button "Log in"
end
+ def log_in_as_club_admin
+ visit "/?locale=en"
+ fill_in "Login", :with => "club_admin"
+ fill_in "Password", :with => "club_admin"
+ uncheck "Remember me"
+ click_button "Log in"
+ end
+
def log_out
visit "/?locale=en"
click_link "Log out"
end
end
|
calmh/Register
|
54b69f24f7e131dfe13009bdb397bd870fa1365d
|
Only extract addresses of non-archived students.
|
diff --git a/bin/ml-members b/bin/ml-members
index 64a501c..faba667 100644
--- a/bin/ml-members
+++ b/bin/ml-members
@@ -1,8 +1,11 @@
#!/usr/bin/env ruby
mailing_list_name = ARGV[0]
mailing_list = MailingList.find_by_email(mailing_list_name)
if mailing_list
- members = mailing_list.students.map { |s| s.email }.reject { |e| e.nil? || e.empty? }
- members.each { |e| puts e}
+ members = mailing_list.students.reject { |student| student.archived == 1 }
+ addresses = members.map { |student| student.email }.reject { |email| email.nil? || email.empty? }
+ addresses.each do |address|
+ puts address
+ end
end
|
calmh/Register
|
f42a5b27a5bb44e1fa91ba723ee1f76b59ca9acd
|
Tweaked display of archived students.
|
diff --git a/app/views/students/archived.html.haml b/app/views/students/archived.html.haml
index 3f7104d..ee3fa60 100644
--- a/app/views/students/archived.html.haml
+++ b/app/views/students/archived.html.haml
@@ -1,23 +1,32 @@
.block
.secondary-navigation
%ul
%li.first= link_to t(:Club_List), clubs_path
%li= link_to h(@club.name), club_path(@club)
%li.last.active= link_to t(:Archived), archived_club_students_path(@club)
.clear
.content
.inner
%h2= t(:Archived)
%p
= t(:Found)
= @students.length
= t(:Archived).downcase
= t(:Students).downcase + "."
%table.table.lesspadding
%tr
%th.first= t(:Name)
+ %th= t(:Main_Interest)
+ %th= t(:Groups)
+ %th= t(:Personal_Num)
+ %th= t(:Grade)
%th.last
- @students.each do |student|
%tr{ :class => cycle("odd", "even") }
- %td= link_to student.name, student_path(student)
+ %td= student.name
+ %td= student.main_interest.category
+ %td= student.groups.map{ |g| g.identifier }.join(", ")
+ %td= student.personal_number
+ %td= grade_str(student.current_grade)
%td= link_to t(:Unarchive), unarchive_student_path(student), :class => 'button'
+ %td
|
calmh/Register
|
fc4eeb3bc78034a26d376b000272d8428eef70d1
|
Extend archived handling
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index b3808d8..e3606f3 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,320 +1,332 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = [ "archived = 0" ]
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def archive
@student = Student.find(params[:id])
@student.archived = 1
@student.save
redirect_to(@student.club)
end
+ def unarchive
+ @student = Student.find(params[:id])
+ @student.archived = 0
+ @student.save
+ redirect_to archived_club_students_path(@student.club)
+ end
+
+ def archived
+ @club = Club.find(params[:club_id])
+ @students = @club.students.archived
+ end
+
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to].keys
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
ml_ids = ml_ids.select do |x|
if cur_ids.include?(x)
true
next
end
ml = MailingList.find(x)
ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index fe1c83c..118150b 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,163 +1,164 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
+ named_scope :archived, :conditions => { :archived => 1 }
named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
:conditions => conditions,
:include => [
{ :graduations => [ :grade_category, :grade ] },
:payments, :club, :groups, :main_interest,
:board_position, :club_position, :title
]
}
}
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
@name ||= fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
@latest_payment ||= if !payments.blank?
payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
payment
end
end
def current_grade
@current_grade ||= calculate_current_grade
end
def calculate_current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
@active ||= if payments.blank?
Time.now - created_at < 86400 * 45
else
Time.now - payments[0].received < 86400 * 180
end
end
def gender=(value)
self[:gender] = value
@gender = nil
end
def gender
@gender ||= if personal_number =~ /-\d\d(\d)\d$/
$1.to_i.even? ? 'female' : 'male'
else
self[:gender] || 'unknown'
end
end
def age
@age ||= if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
((Date.today - date_of_birth) / 365.24).to_i
else
nil
end
end
def group_list
@group_list ||= groups.map{ |group| group.identifier }.join(", ")
end
end
diff --git a/app/views/students/archived.html.haml b/app/views/students/archived.html.haml
new file mode 100644
index 0000000..3f7104d
--- /dev/null
+++ b/app/views/students/archived.html.haml
@@ -0,0 +1,23 @@
+.block
+ .secondary-navigation
+ %ul
+ %li.first= link_to t(:Club_List), clubs_path
+ %li= link_to h(@club.name), club_path(@club)
+ %li.last.active= link_to t(:Archived), archived_club_students_path(@club)
+ .clear
+ .content
+ .inner
+ %h2= t(:Archived)
+ %p
+ = t(:Found)
+ = @students.length
+ = t(:Archived).downcase
+ = t(:Students).downcase + "."
+ %table.table.lesspadding
+ %tr
+ %th.first= t(:Name)
+ %th.last
+ - @students.each do |student|
+ %tr{ :class => cycle("odd", "even") }
+ %td= link_to student.name, student_path(student)
+ %td= link_to t(:Unarchive), unarchive_student_path(student), :class => 'button'
diff --git a/app/views/students/index.html.haml b/app/views/students/index.html.haml
index bd52441..d6b05fa 100644
--- a/app/views/students/index.html.haml
+++ b/app/views/students/index.html.haml
@@ -1,15 +1,16 @@
.block
.secondary-navigation
%ul
- if [email protected]?
%li.first= link_to t(:Club_List), clubs_path
- %li.active.last= link_to h(@club.name), club_path(@club)
+ %li.active= link_to h(@club.name), club_path(@club)
+ %li.last= link_to t(:Archived), archived_club_students_path(@club)
- else
%li.first.active.last= link_to t(:Search_Students), students_path
.clear
.content
.inner
%h2= t(:Students)
= render :partial => 'list'
= content_for :sidebar, render(:partial => 'clubs/sidebar')
diff --git a/config/locales/en.yml b/config/locales/en.yml
index fb0e6f4..1ce0dbf 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,211 +1,214 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The club will be deleted.
Are_you_sure_archive: Are you sure? The student will be archived, and thus hidden from view until unarchived.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
Welcome_Text: Welcome Text
Welcome_Text_descr: "This is the text that is sent in the welcome email. Use the placeholders %club%, %url% and %password% to denote the current club, URL to log in at and the user's password.."
Archive: Archive
+ Archived: Archived
+ Unarchive: Make Active
+ Found: Found
activerecord:
messages:
in_future: in the future
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 8658674..05b92f0 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,286 +1,289 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_archive: Ãr du säker? Eleven kommer att arkiveras, och därmed vara dold tills han/hon aktiveras igen.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
Body_text: Brödtext
Send: Skicka
Subject: Ãrende
From: Från
Back: Tillbaka
Message_sent_to: Meddelandet skickades till
Couldnt_send_to: Kunde inte skicka meddelande till
because_no_email: eftersom de inte har en epostadress.
Welcome_Text: Välkomsttext
Welcome_Text_descr: "Detta är den text som skickas ut i välkomstbrevet. Använd platshållarna %club%, %url% och %password% för att hänvisa till den aktuella klubben, URL:en att logga in på samt användarens lösenord."
Archive: Arkivera
+ Archived: Arkiverade
+ Unarchive: Gör aktiv igen
+ Found: Hittade
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
in_future: i framtiden
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/config/routes.rb b/config/routes.rb
index d6fe5c1..3016570 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,81 +1,81 @@
ActionController::Routing::Routes.draw do |map|
# For debugging, check validations
map.validate 'validate', :controller => 'application', :action => 'validate'
map.edit_site 'edit_site_settings', :controller => 'application', :action => 'edit_site_settings'
map.update_site 'update_site_settings', :controller => 'application', :action => 'update_site_settings'
# Bulk operations
map.connect 'students/bulkoperations', :controller => 'students', :action => 'bulk_operations'
map.connect 'graduations/new_bulk', :controller => 'graduations', :action => 'new_bulk'
map.connect 'graduations/update_bulk', :controller => 'graduations', :action => 'update_bulk'
map.connect 'payments/new_bulk', :controller => 'payments', :action => 'new_bulk'
map.connect 'payments/update_bulk', :controller => 'payments', :action => 'update_bulk'
# Clubs, students and subresources
map.resources :clubs, :shallow => true do |club|
- club.resources :students, :collection => { :filter => :post }, :member => { :archive => :get } do |student|
+ club.resources :students, :collection => { :filter => :post, :archived => :get }, :member => { :archive => :get, :unarchive => :get } do |student|
student.resources :payments
student.resources :graduations
end
end
map.resources :students, :only => :index
# Other singular resources
map.resources :administrators
map.resources :groups
map.resources :mailing_lists
map.resources :messages
# For login and logout
map.resource :user_session
# Password reset
map.resources :password_resets
# Display club list at /
map.root :controller => :clubs
# map.root :controller => "user_sessions", :action => "new"
# 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/seeds.rb b/db/seeds.rb
index ea70e61..1377e22 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,51 +1,58 @@
Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
admin = Factory(:administrator, :login => 'admin',
:password => 'admin', :password_confirmation => 'admin',
:groups_permission => true,
:mailinglists_permission => true,
:clubs_permission => true,
:users_permission => true,
:site_permission => true
)
# Create two clubs with a few basic students in
clubs = 2.times.map { Factory(:club) }
Factory(:student, :club => clubs[0], :email => "[email protected]", :password => "student", :password_confirmation => "student")
clubs.each do |club|
10.times do
Factory(:student, :club => club)
end
end
6.times do
# Create one club with a lot more students and data
club = Factory(:club)
clubs << club
grades = 3.times.map { Factory(:grade) }
groups = 3.times.map { Factory(:group) }
mailing_lists = 3.times.map { Factory(:mailing_list) }
150.times do
student = Factory(:student, :club => club)
grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
mailing_lists.each { |ml| student.mailing_lists << ml }
groups.each { |ml| student.groups << ml }
3.times { Factory(:payment, :student => student) }
end
+ 20.times do
+ student = Factory(:student, :club => club, :archived => 1)
+ grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
+ mailing_lists.each { |ml| student.mailing_lists << ml }
+ groups.each { |ml| student.groups << ml }
+ 3.times { Factory(:payment, :student => student) }
+ end
end
%w[read edit delete graduations payments export].each do |perm|
clubs.each do |club|
Factory(:permission, :club => club, :user => admin, :permission => perm)
end
end
4.times do
Factory(:mailing_list)
end
4.times do
Factory(:group)
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index c193f8f..bab9dca 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,263 +1,293 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
test "student page should show all students" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should show only this club's students" do
other_club = Factory(:club)
other_students = 10.times.map { Factory(:student, :club => other_club )}
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
other_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "student page should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
archived_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
+ test "archived page should display only archived students" do
+ archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "Archived"
+ @students.each do |s|
+ assert_not_contain Regexp.new("\\b" + s.name + "\\b")
+ end
+ archived_students.each do |s|
+ assert_contain Regexp.new("\\b" + s.name + "\\b")
+ end
+ end
+
+ test "unarchive student should remove him/her from archived page" do
+ archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "Archived"
+ visit "/students/#{archived_students[0].id}/unarchive"
+ assert_not_contain Regexp.new("\\b" + archived_students[0].name + "\\b")
+ archived_students.delete_at 0
+ archived_students.each do |s|
+ assert_contain Regexp.new("\\b" + s.name + "\\b")
+ end
+ end
+
test "overview page student count should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
assert_contain Regexp.new("\\b#{@students.length}\\b")
assert_not_contain Regexp.new("\\b#{@students.length + archived_students.length}\\b")
end
test "student should be archived and then not be listed on the club page" do
archived = @students[0]
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link archived.name
click_link "Edit"
click_link "Archive"
click_link @club.name
assert_not_contain archived.name
end
test "should not create new blank student" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
click_button "Save"
assert_not_contain "created"
assert_contain "can't be blank"
end
test "should create new student with minimal info" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
select @category.category
click_button "Save"
assert_contain "created"
end
test "should create a new student in x groups" do
@admin.groups_permission = true
@admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_groups.each do |g|
check g.identifier
end
click_button "Save"
assert_contain "created"
member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_contain "Test Testsson"
end
non_member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_not_contain "Test Testsson"
end
end
test "should create a new student in x mailing lists" do
@admin.mailinglists_permission = true
@admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_lists.each do |m|
check m.description
end
click_button "Save"
assert_contain "created"
member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_contain "Test Testsson"
end
non_member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_not_contain "Test Testsson"
end
end
test "new student should join club mailing list per default" do
mailing_list = Factory(:mailing_list, :default => 1)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
other_club = Factory(:club)
mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_not_contain "Test Testsson"
end
test "student should be able to edit self without losing groups" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
group = Factory(:group)
student.groups << group;
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.groups.length == 1
end
test "student should join mailing list" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_list = Factory(:mailing_list)
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_list.description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == [ mailing_list.id ]
end
test "student should join one mailing list and leave another" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
end
end
|
calmh/Register
|
03938c795f1b026956f04974a3fef54ee79ca781
|
Mailing lists should be sorted by email
|
diff --git a/app/controllers/mailing_lists_controller.rb b/app/controllers/mailing_lists_controller.rb
index 7ac6f09..ed5745b 100644
--- a/app/controllers/mailing_lists_controller.rb
+++ b/app/controllers/mailing_lists_controller.rb
@@ -1,44 +1,44 @@
class MailingListsController < ApplicationController
before_filter :require_mailing_lists_permission
def index
- @mailing_lists = MailingList.find(:all)
+ @mailing_lists = MailingList.find(:all, :order => "email")
end
def new
@mailing_list = MailingList.new
end
def edit
@mailing_list = MailingList.find(params[:id])
end
def create
@mailing_list = MailingList.new(params[:mailing_list])
if @mailing_list.save
flash[:notice] = t:Mailing_list_created
redirect_to(mailing_lists_path)
else
render :action => "new"
end
end
def update
@mailing_list = MailingList.find(params[:id])
if @mailing_list.update_attributes(params[:mailing_list])
flash[:notice] = t:Mailing_list_updated
redirect_to(mailing_lists_path)
else
render :action => "edit"
end
end
def destroy
@mailing_list = MailingList.find(params[:id])
@mailing_list.destroy
redirect_to(mailing_lists_path)
end
end
diff --git a/test/integration/mailing_list_test.rb b/test/integration/mailing_list_test.rb
index f6e5895..76eafe5 100644
--- a/test/integration/mailing_list_test.rb
+++ b/test/integration/mailing_list_test.rb
@@ -1,158 +1,170 @@
require 'test_helper'
class MailingListTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@admin.mailinglists_permission = true
@admin.save
- @mailing_lists = 4.times.map { Factory(:mailing_list) }
+ @mailing_lists = []
+ @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Zz List")
+ @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Bb List")
+ @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Cc List")
+ @mailing_lists << Factory(:mailing_list, :email => "[email protected]", :description => "Aa List")
+
@students = 5.times.map { Factory(:student) }
@unsorted_students = [ Factory(:student, :fname => "Bb", :sname => "Bb"),
Factory(:student, :fname => "Aa", :sname => "Aa"),
Factory(:student, :fname => "Zz", :sname => "Zz") ]
@member_list = @mailing_lists[0]
@students.each do |s|
s.mailing_lists << @member_list
s.save
end
end
test "mailing lists should be displayed on the list page" do
log_in_as_admin
click_link "Mailing lists"
@mailing_lists.each do |m|
assert_contain m.email
assert_contain m.description
end
end
+ test "mailing lists should be displayed on the list page, and should be sorted by email" do
+ log_in_as_admin
+
+ click_link "Mailing lists"
+ assert_contain /aa@example.*bb@example.*cc@example.*zz@example/m
+ end
+
test "should create new mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => "[email protected]"
fill_in "Description", :with => "A test list"
fill_in "Security", :with => "public"
click_button "Save"
click_link "Mailing lists"
assert_contain "[email protected]"
assert_contain "A test list"
end
test "should delete a mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link @mailing_lists[0].email
click_link "Destroy"
click_link "Mailing lists"
assert_not_contain @mailing_lists[0].email
end
test "should not be able to create a new mailing list with non-unique email" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => @mailing_lists[0].email
fill_in "Description", :with => "A test list"
fill_in "Security", :with => "public"
click_button "Save"
assert_contain "taken"
end
test "mailing list should show members" do
log_in_as_admin
click_link "Mailing lists"
click_link @member_list.email
@students.each do |s|
assert_contain s.name
end
end
test "mailing list should display students sorted by name, even if added randomly" do
log_in_as_admin
@unsorted_students.each do |student|
click_link @club.name
click_link student.name
click_link "Edit"
check @mailing_lists[2].description
click_button "Save"
end
click_link "Mailing lists"
click_link @mailing_lists[2].email
assert_contain /Aa Aa.*Bb Bb.*Zz Zz/m
end
test "remove student from mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
assert_not_contain @member_list.description
end
test "remove student from mailing list, and verify this on the membership page" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
click_link "Mailing lists"
click_link @member_list.email
assert_not_contain @students[0].name
end
test "add student to one mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
click_button "Save"
assert_contain @mailing_lists[1].description
end
test "add student to two mailing lists" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
check @mailing_lists[2].description
click_button "Save"
assert_contain @mailing_lists[1].description
assert_contain @mailing_lists[2].description
end
end
|
calmh/Register
|
0bc3bc950452e90beb0bec24be855cac8246bd91
|
Order students on mailing list page by name.
|
diff --git a/app/models/mailing_list.rb b/app/models/mailing_list.rb
index 4cb92ca..6dffc77 100644
--- a/app/models/mailing_list.rb
+++ b/app/models/mailing_list.rb
@@ -1,7 +1,7 @@
class MailingList < ActiveRecord::Base
- has_and_belongs_to_many :students
+ has_and_belongs_to_many :students, :order => "fname, sname"
belongs_to :club
validates_format_of :security, :with => /^public|private$/
validates_format_of :email, :with => /^[a-z_.0-9-]+@[a-z0-9.-]+/
validates_uniqueness_of :email
end
diff --git a/test/integration/mailing_list_test.rb b/test/integration/mailing_list_test.rb
index e571d61..f6e5895 100644
--- a/test/integration/mailing_list_test.rb
+++ b/test/integration/mailing_list_test.rb
@@ -1,139 +1,158 @@
require 'test_helper'
class MailingListTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@admin.mailinglists_permission = true
@admin.save
@mailing_lists = 4.times.map { Factory(:mailing_list) }
@students = 5.times.map { Factory(:student) }
+ @unsorted_students = [ Factory(:student, :fname => "Bb", :sname => "Bb"),
+ Factory(:student, :fname => "Aa", :sname => "Aa"),
+ Factory(:student, :fname => "Zz", :sname => "Zz") ]
@member_list = @mailing_lists[0]
@students.each do |s|
s.mailing_lists << @member_list
s.save
end
end
test "mailing lists should be displayed on the list page" do
log_in_as_admin
click_link "Mailing lists"
@mailing_lists.each do |m|
assert_contain m.email
assert_contain m.description
end
end
test "should create new mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => "[email protected]"
fill_in "Description", :with => "A test list"
fill_in "Security", :with => "public"
click_button "Save"
click_link "Mailing lists"
assert_contain "[email protected]"
assert_contain "A test list"
end
test "should delete a mailing list" do
log_in_as_admin
click_link "Mailing lists"
click_link @mailing_lists[0].email
click_link "Destroy"
click_link "Mailing lists"
assert_not_contain @mailing_lists[0].email
end
test "should not be able to create a new mailing list with non-unique email" do
log_in_as_admin
click_link "Mailing lists"
click_link "New mailing list"
fill_in "Email", :with => @mailing_lists[0].email
fill_in "Description", :with => "A test list"
fill_in "Security", :with => "public"
click_button "Save"
assert_contain "taken"
end
test "mailing list should show members" do
log_in_as_admin
click_link "Mailing lists"
click_link @member_list.email
@students.each do |s|
assert_contain s.name
end
end
+ test "mailing list should display students sorted by name, even if added randomly" do
+ log_in_as_admin
+
+ @unsorted_students.each do |student|
+ click_link @club.name
+ click_link student.name
+ click_link "Edit"
+ check @mailing_lists[2].description
+ click_button "Save"
+ end
+
+ click_link "Mailing lists"
+ click_link @mailing_lists[2].email
+ assert_contain /Aa Aa.*Bb Bb.*Zz Zz/m
+ end
+
test "remove student from mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
assert_not_contain @member_list.description
end
test "remove student from mailing list, and verify this on the membership page" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
uncheck @member_list.description
click_button "Save"
click_link "Mailing lists"
click_link @member_list.email
assert_not_contain @students[0].name
end
test "add student to one mailing list" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
click_button "Save"
assert_contain @mailing_lists[1].description
end
test "add student to two mailing lists" do
log_in_as_admin
click_link @club.name
click_link @students[0].name
click_link "Edit"
check @mailing_lists[1].description
check @mailing_lists[2].description
click_button "Save"
assert_contain @mailing_lists[1].description
assert_contain @mailing_lists[2].description
end
end
|
calmh/Register
|
908c415e09d000581cc9f52a7bb3974a7b414504
|
Fix bug with updating mailing list memebership as administrator.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index a58344c..b3808d8 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,320 +1,320 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = [ "archived = 0" ]
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def archive
@student = Student.find(params[:id])
@student.archived = 1
@student.save
redirect_to(@student.club)
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
- ml_ids = params[:subscribes_to]
+ ml_ids = params[:subscribes_to].keys
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
- ml_ids = ml_ids.keys.select do |x|
+ ml_ids = ml_ids.select do |x|
if cur_ids.include?(x)
true
next
end
ml = MailingList.find(x)
ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
|
calmh/Register
|
8171d7ec02a03d73ea5c8eb60ea16c7075db2526
|
Reindent and add tests for mailing list management (administrator)
|
diff --git a/test/integration/mailing_list_test.rb b/test/integration/mailing_list_test.rb
index ce41672..e571d61 100644
--- a/test/integration/mailing_list_test.rb
+++ b/test/integration/mailing_list_test.rb
@@ -1,111 +1,139 @@
require 'test_helper'
class MailingListTest < ActionController::IntegrationTest
- def setup
+ def setup
create_club_and_admin
@admin.mailinglists_permission = true
@admin.save
@mailing_lists = 4.times.map { Factory(:mailing_list) }
@students = 5.times.map { Factory(:student) }
@member_list = @mailing_lists[0]
@students.each do |s|
s.mailing_lists << @member_list
s.save
end
end
test "mailing lists should be displayed on the list page" do
- log_in_as_admin
+ log_in_as_admin
- click_link "Mailing lists"
+ click_link "Mailing lists"
- @mailing_lists.each do |m|
- assert_contain m.email
- assert_contain m.description
- end
+ @mailing_lists.each do |m|
+ assert_contain m.email
+ assert_contain m.description
+ end
end
- test "should create new mailing list" do
- log_in_as_admin
+ test "should create new mailing list" do
+ log_in_as_admin
- click_link "Mailing lists"
- click_link "New mailing list"
+ click_link "Mailing lists"
+ click_link "New mailing list"
- fill_in "Email", :with => "[email protected]"
- fill_in "Description", :with => "A test list"
- fill_in "Security", :with => "public"
+ fill_in "Email", :with => "[email protected]"
+ fill_in "Description", :with => "A test list"
+ fill_in "Security", :with => "public"
- click_button "Save"
- click_link "Mailing lists"
+ click_button "Save"
+ click_link "Mailing lists"
- assert_contain "[email protected]"
- assert_contain "A test list"
- end
+ assert_contain "[email protected]"
+ assert_contain "A test list"
+ end
- test "should delete a mailing list" do
- log_in_as_admin
+ test "should delete a mailing list" do
+ log_in_as_admin
- click_link "Mailing lists"
- click_link @mailing_lists[0].email
+ click_link "Mailing lists"
+ click_link @mailing_lists[0].email
click_link "Destroy"
- click_link "Mailing lists"
- assert_not_contain @mailing_lists[0].email
- end
+ click_link "Mailing lists"
+ assert_not_contain @mailing_lists[0].email
+ end
- test "should not be able to create a new mailing list with non-unique email" do
- log_in_as_admin
+ test "should not be able to create a new mailing list with non-unique email" do
+ log_in_as_admin
- click_link "Mailing lists"
- click_link "New mailing list"
+ click_link "Mailing lists"
+ click_link "New mailing list"
- fill_in "Email", :with => @mailing_lists[0].email
- fill_in "Description", :with => "A test list"
- fill_in "Security", :with => "public"
+ fill_in "Email", :with => @mailing_lists[0].email
+ fill_in "Description", :with => "A test list"
+ fill_in "Security", :with => "public"
- click_button "Save"
- assert_contain "taken"
- end
+ click_button "Save"
+ assert_contain "taken"
+ end
test "mailing list should show members" do
- log_in_as_admin
+ log_in_as_admin
- click_link "Mailing lists"
- click_link @member_list.email
+ click_link "Mailing lists"
+ click_link @member_list.email
@students.each do |s|
assert_contain s.name
end
end
- test "remove student from mailing list" do
- log_in_as_admin
+ test "remove student from mailing list" do
+ log_in_as_admin
+
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
+
+ uncheck @member_list.description
+ click_button "Save"
+
+ assert_not_contain @member_list.description
+ end
+
+ test "remove student from mailing list, and verify this on the membership page" do
+ log_in_as_admin
click_link @club.name
- click_link @students[0].name
- click_link "Edit"
+ click_link @students[0].name
+ click_link "Edit"
- uncheck @member_list.description
- click_button "Save"
+ uncheck @member_list.description
+ click_button "Save"
- assert_not_contain @member_list.description
- end
+ click_link "Mailing lists"
+ click_link @member_list.email
+ assert_not_contain @students[0].name
+ end
- test "remove student from mailing list, and verify this on the membership page" do
- log_in_as_admin
+ test "add student to one mailing list" do
+ log_in_as_admin
click_link @club.name
- click_link @students[0].name
- click_link "Edit"
+ click_link @students[0].name
+ click_link "Edit"
+
+ check @mailing_lists[1].description
+ click_button "Save"
+
+ assert_contain @mailing_lists[1].description
+ end
- uncheck @member_list.description
- click_button "Save"
+ test "add student to two mailing lists" do
+ log_in_as_admin
- click_link "Mailing lists"
- click_link @member_list.email
- assert_not_contain @students[0].name
- end
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
+
+ check @mailing_lists[1].description
+ check @mailing_lists[2].description
+ click_button "Save"
+
+ assert_contain @mailing_lists[1].description
+ assert_contain @mailing_lists[2].description
+ end
end
|
calmh/Register
|
93e639378e48b26cc1a7ad6f79bee063b36912f0
|
Some cleanups and extra tests.
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index cc62e7d..440efda 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,174 +1,130 @@
-# Filters added to this controller apply to all controllers in the application.
-# Likewise, all the methods added will be available for all controllers.
-
-class SiteSettings
- def self.get_setting(setting_name)
- setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
- return "" if setting == nil
- return setting.value
- end
-
- def self.set_setting(setting_name, value)
- setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
- if setting == nil
- setting = ConfigurationSetting.new
- setting.setting = setting_name
- end
- setting.value = value
- setting.save!
- end
-
- def self.site_name
- get_setting(:site_name)
- end
- def self.site_name=(value)
- set_setting(:site_name, value)
- end
-
- def self.site_theme
- get_setting(:site_theme)
- end
- def self.site_theme=(value)
- set_setting(:site_theme, value)
- end
-
- def self.welcome_text
- get_setting(:welcome_text)
- end
- def self.welcome_text=(value)
- set_setting(:welcome_text, value)
- end
-end
-
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user
before_filter :set_locale
- protect_from_forgery # :secret => '4250e2ff2a2308b6668755ef76677cbb'
+ protect_from_forgery
before_filter :require_site_permission, :only => [ :edit_site_settings, :update_site_settings ]
- def set_locale
- session[:locale] = params[:locale] if params[:locale] != nil
- I18n.locale = session[:locale] if session[:locale] != nil
- end
-
def edit_site_settings
@available_themes = Dir.entries("public/stylesheets/themes").select { |entry| !entry.starts_with? '.' }.sort
+ render
end
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
SiteSettings.welcome_text = params[:welcome_text]
+
expire_fragment('layout_header')
+
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
- def validate
- require_administrator end
+ def set_locale
+ session[:locale] = params[:locale] if params[:locale] != nil
+ I18n.locale = session[:locale] if session[:locale] != nil
+ end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
- def denied
- store_location
- flash[:warning] = t(:Must_log_in)
- current_user_session.destroy if current_user_session
- redirect_to new_user_session_path
- return false
- end
-
def require_student_or_administrator
return denied unless current_user
return true
end
def require_administrator_or_self(student)
return denied unless current_user.type == 'Administrator' || current_user == student
return true
end
def require_administrator
return denied unless current_user && current_user.type == 'Administrator'
return true
end
def require_clubs_permission
- return denied unless current_user
- return denied unless current_user.clubs_permission?
- return true
+ require_permission(:clubs_permission?)
end
def require_groups_permission
- return denied unless current_user
- return denied unless current_user.groups_permission?
- return true
+ require_permission(:groups_permission?)
end
def require_users_permission
- return denied unless current_user
- return denied unless current_user.users_permission?
- return true
+ require_permission(:users_permission?)
end
def require_mailing_lists_permission
- return denied unless current_user
- return denied unless current_user.mailinglists_permission?
- return true
+ require_permission(:mailinglists_permission?)
end
def require_site_permission
- return denied unless current_user
- return denied unless current_user.site_permission?
- return true
+ require_permission(:site_permission?)
end
def require_export_permission(club)
return denied unless current_user
return denied unless current_user.export_permission?(club)
return true
end
def require_no_user
if current_user
store_location
redirect_to current_user
return false
end
return true
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def get_default(key)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
val.try(:value)
end
def set_default(key, value)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
if val == nil
val = DefaultValue.new
val.user_id = current_user.id
val.key = key
end
val.value = value
val.save!
end
+
+ private
+
+ def require_permission(permission)
+ return denied unless current_user
+ return denied unless current_user.send(permission)
+ return true
+ end
+
+ def denied
+ store_location
+ flash[:warning] = t(:Must_log_in)
+ current_user_session.destroy if current_user_session
+ redirect_to new_user_session_path
+ return false
+ end
end
diff --git a/app/models/group.rb b/app/models/group.rb
index 2d8e75c..b6188b4 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -1,16 +1,12 @@
class Group < ActiveRecord::Base
has_and_belongs_to_many :students, :order => "sname, fname"
- def members_in(club)
- return students.find(:all, :conditions => { :club_id => club.id })
- end
-
def merge_into(destination)
merge_ids = destination.student_ids
self.students.each do |student|
destination.students << student unless merge_ids.include?(student.id)
end
destination.save!
destroy
end
end
diff --git a/app/models/notifier.rb b/app/models/notifier.rb
index 4072869..ff516f3 100644
--- a/app/models/notifier.rb
+++ b/app/models/notifier.rb
@@ -1,19 +1,19 @@
class Notifier < ActionMailer::Base
default_url_options[:host] = "www.fiveforms.org"
def password_reset_instructions(user)
- subject "Password Reset Instructions"
- from "[email protected]"
- recipients user.email
- sent_on Time.now
- body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
+ subject "Password Reset Instructions"
+ from "[email protected]"
+ recipients user.email
+ sent_on Time.now
+ body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
end
def generic_message(user, message)
- subject message.subject
- from message.from
- recipients user.email
- sent_on Time.now
- body message.body
+ subject message.subject
+ from message.from
+ recipients user.email
+ sent_on Time.now
+ body message.body
end
end
diff --git a/app/models/site_settings.rb b/app/models/site_settings.rb
new file mode 100644
index 0000000..fa1e1c1
--- /dev/null
+++ b/app/models/site_settings.rb
@@ -0,0 +1,39 @@
+class SiteSettings
+ def self.get_setting(setting_name)
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
+ return "" if setting == nil
+ return setting.value
+ end
+
+ def self.set_setting(setting_name, value)
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
+ if setting == nil
+ setting = ConfigurationSetting.new
+ setting.setting = setting_name
+ end
+ setting.value = value
+ setting.save!
+ end
+
+ def self.site_name
+ get_setting(:site_name)
+ end
+ def self.site_name=(value)
+ set_setting(:site_name, value)
+ end
+
+ def self.site_theme
+ get_setting(:site_theme)
+ end
+ def self.site_theme=(value)
+ set_setting(:site_theme, value)
+ end
+
+ def self.welcome_text
+ get_setting(:welcome_text)
+ end
+ def self.welcome_text=(value)
+ set_setting(:welcome_text, value)
+ end
+end
+
diff --git a/test/unit/administrator_test.rb b/test/unit/administrator_test.rb
index 005a30e..410c65d 100644
--- a/test/unit/administrator_test.rb
+++ b/test/unit/administrator_test.rb
@@ -1,12 +1,29 @@
require 'test_helper'
class AdministratorTest < ActiveSupport::TestCase
def setup
@admin = Factory(:administrator)
+ @club = Factory(:club)
end
test "administrator must have a login" do
@admin.login = nil
assert [email protected]?
end
+
+ test "permissions for club should return all permissions for that club" do
+ permissions = %w[read edit delete payments graduations export]
+ permissions.each do |perm|
+ Factory(:permission, :permission => perm, :user => @admin, :club => @club)
+ end
+
+ permissions_for_club = @admin.permissions_for(@club)
+ permissions.each do |perm|
+ assert permissions_for_club.include? perm
+ end
+ end
+
+ test "permissions for club should return nothin by default" do
+ assert_equal [], @admin.permissions_for(@club)
+ end
end
diff --git a/test/unit/group_test.rb b/test/unit/group_test.rb
new file mode 100644
index 0000000..486d549
--- /dev/null
+++ b/test/unit/group_test.rb
@@ -0,0 +1,33 @@
+require 'test_helper'
+
+class GroupTest < ActiveSupport::TestCase
+ def setup
+ @group_a = Factory(:group)
+ @group_b = Factory(:group)
+ @students_a = []
+ @students_b = []
+ 10.times do
+ @students_a << Factory(:student)
+ @students_a.last.groups << @group_a
+ @students_b << Factory(:student)
+ @students_b.last.groups << @group_b
+ end
+ end
+
+ test "group contains it's students" do
+ assert_equal @students_a.map(&:id).sort, @group_a.students.map(&:id).sort
+ end
+
+ test "merged group contains all students" do
+ @group_a.merge_into(@group_b)
+ total_student_list = (@students_a + @students_b).map(&:id).sort
+ merged_students_list = @group_b.students.map(&:id).sort
+ assert_equal total_student_list, merged_students_list
+ end
+
+ test "source group in merge contains no students" do
+ @group_a.merge_into(@group_b)
+ remaining_students_list = @group_a.students.map(&:id).sort
+ assert_equal [], remaining_students_list
+ end
+end
|
calmh/Register
|
ac2853e9220b9d124e0a6c7c7ed7716839d2abae
|
Don't require personal number by default (matches production environment)
|
diff --git a/config/environment.rb b/config/environment.rb
index 695be09..d221eb0 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,97 +1,97 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
-REQUIRE_PERSONAL_NUMBER = true
+REQUIRE_PERSONAL_NUMBER = false
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
|
calmh/Register
|
a1c38f3e7d59cdca40072d0b6fa3d04936565f12
|
Minor corrections to statistics
|
diff --git a/app/models/student.rb b/app/models/student.rb
index 0c4a596..fe1c83c 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,163 +1,163 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
:conditions => conditions,
:include => [
{ :graduations => [ :grade_category, :grade ] },
:payments, :club, :groups, :main_interest,
:board_position, :club_position, :title
]
}
}
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
@name ||= fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
@latest_payment ||= if !payments.blank?
payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
payment
end
end
def current_grade
@current_grade ||= calculate_current_grade
end
def calculate_current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
@active ||= if payments.blank?
Time.now - created_at < 86400 * 45
else
Time.now - payments[0].received < 86400 * 180
end
end
def gender=(value)
self[:gender] = value
@gender = nil
end
def gender
@gender ||= if personal_number =~ /-\d\d(\d)\d$/
$1.to_i.even? ? 'female' : 'male'
else
self[:gender] || 'unknown'
end
end
def age
@age ||= if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
((Date.today - date_of_birth) / 365.24).to_i
else
- -1
+ nil
end
end
def group_list
@group_list ||= groups.map{ |group| group.identifier }.join(", ")
end
end
diff --git a/app/views/students/_statistics.html.haml b/app/views/students/_statistics.html.haml
index bfa80d7..17a9ebf 100644
--- a/app/views/students/_statistics.html.haml
+++ b/app/views/students/_statistics.html.haml
@@ -1,37 +1,38 @@
.block
%h3= t(:Statistics)
.content
%p
= t(:Matched_x_students, :count => @students.length)
- total = @students.length
- age_intervals = {}
- [ [0,7], [8,14], [15,20], [21,25], [26,99] ].each do |from, to|
- from.upto(to) { |age| age_intervals[age] = "#{from}‑#{to} " + t(:years) }
- group_members = Hash.new(0)
- genders = Hash.new(0)
- ages = Hash.new(0)
- board_positions = Hash.new(0)
- club_positions = Hash.new(0)
- main_interests = Hash.new(0)
- titles = Hash.new(0)
- @students.each do |student|
- student.groups.each do |group|
- group_members[group.identifier] += 1
- genders[student.gender] += 1
- - ages[age_intervals[student.age]] += 1
+ - if !student.age.nil?
+ - ages[age_intervals[student.age]] += 1
- board_positions[student.board_position.position] += 1
- club_positions[student.club_position.position] += 1
- main_interests[student.main_interest.category] += 1
- titles[student.title.title] += 1
= render :partial => 'statistics_table', :locals => { :col1 => t(:Group), :col2 => t(:Num_Students), :rows => group_members.to_a.sort, :total => total }
- = render :partial => 'statistics_table', :locals => { :col1 => t(:Gender), :col2 => t(:Num_Students), :rows => genders.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Gender), :col2 => t(:Num_Students), :rows => genders.to_a.map{|x| [ t(x[0]).titlecase, x[1] ]}.sort, :total => total }
= render :partial => 'statistics_table', :locals => { :col1 => t(:Age), :col2 => t(:Num_Students), :rows => ages.to_a.sort, :total => total }
= render :partial => 'statistics_table', :locals => { :col1 => t(:Board_Position), :col2 => t(:Num_Students), :rows => board_positions.to_a.sort, :total => total }
= render :partial => 'statistics_table', :locals => { :col1 => t(:Club_Position), :col2 => t(:Num_Students), :rows => club_positions.to_a.sort, :total => total }
= render :partial => 'statistics_table', :locals => { :col1 => t(:Main_Interest), :col2 => t(:Num_Students), :rows => main_interests.to_a.sort, :total => total }
= render :partial => 'statistics_table', :locals => { :col1 => t(:Title), :col2 => t(:Num_Students), :rows => titles.to_a.sort, :total => total }
|
calmh/Register
|
c6967e1c54bc41393684d705e98cde7f85bc89ce
|
Seriously improved performance of statistics.
|
diff --git a/app/views/students/_statistics.html.erb b/app/views/students/_statistics.html.erb
deleted file mode 100644
index f2bcae4..0000000
--- a/app/views/students/_statistics.html.erb
+++ /dev/null
@@ -1,58 +0,0 @@
-<div class="block">
- <h3><%=t(:Statistics)%></h3>
- <div class="content">
- <p>
- <%= t(:Matched_x_students, :count => @students.length) %>.
- <% total = @students.length %>
- </p>
-
- <% rows = [] %>
- <% for group in groups do -%>
- <% count = @students.select{ |s| s.group_ids.include? group.id }.length -%>
- <% rows << [ group.identifier, count ] %>
- <% end %>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Group), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <% rows = [] %>
- <% rows << [ t(:Male), @students.select{ |s| s.gender == 'male' }.length ] -%>
- <% rows << [ t(:Female), @students.select{ |s| s.gender == 'female' }.length ] -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Gender), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <%- rows = [] -%>
- <%- ages = [ [0,7], [8,14], [15,20], [21,25], [26,99] ] -%>
- <%- for age_span in ages do -%>
- <%- l = age_span[0].to_s + "‑" + age_span[1].to_s + " " + t(:years) -%>
- <%- c = @students.select{ |s| s.age >= age_span[0] && s.age <= age_span[1] }.length %>
- <%- rows << [ l, c ] -%>
- <%- end -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Age), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <%- rows = [] -%>
- <%- for position in board_positions do -%>
- <%- c = @students.select{ |s| s.board_position == position }.length -%>
- <%- rows << [ position.position, c ] -%>
- <%- end -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Board_Position), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <%- rows = [] -%>
- <%- for position in club_positions do -%>
- <%- c = @students.select{ |s| s.club_position == position }.length -%>
- <%- rows << [ position.position, c ] -%>
- <%- end -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Club_Position), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <%- rows = [] -%>
- <%- for category in grade_categories do -%>
- <%- c = @students.select{ |s| s.main_interest == category }.length -%>
- <%- rows << [ category.category, c ] -%>
- <%- end -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Main_Interest), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
-
- <%- rows = [] -%>
- <%- for title in titles do -%>
- <%- c = @students.select{ |s| s.title == title }.length -%>
- <%- rows << [ title.title, c ] -%>
- <%- end -%>
- <%= render :partial => 'statistics_table', :locals => { :col1 => t(:Title), :col2 => t(:Num_Students), :rows => rows, :total => total } -%>
- </div>
-</div>
diff --git a/app/views/students/_statistics.html.haml b/app/views/students/_statistics.html.haml
new file mode 100644
index 0000000..bfa80d7
--- /dev/null
+++ b/app/views/students/_statistics.html.haml
@@ -0,0 +1,37 @@
+.block
+ %h3= t(:Statistics)
+ .content
+ %p
+ = t(:Matched_x_students, :count => @students.length)
+ - total = @students.length
+
+ - age_intervals = {}
+ - [ [0,7], [8,14], [15,20], [21,25], [26,99] ].each do |from, to|
+ - from.upto(to) { |age| age_intervals[age] = "#{from}‑#{to} " + t(:years) }
+
+ - group_members = Hash.new(0)
+ - genders = Hash.new(0)
+ - ages = Hash.new(0)
+ - board_positions = Hash.new(0)
+ - club_positions = Hash.new(0)
+ - main_interests = Hash.new(0)
+ - titles = Hash.new(0)
+ - @students.each do |student|
+ - student.groups.each do |group|
+ - group_members[group.identifier] += 1
+ - genders[student.gender] += 1
+ - ages[age_intervals[student.age]] += 1
+ - board_positions[student.board_position.position] += 1
+ - club_positions[student.club_position.position] += 1
+ - main_interests[student.main_interest.category] += 1
+ - titles[student.title.title] += 1
+
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Group), :col2 => t(:Num_Students), :rows => group_members.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Gender), :col2 => t(:Num_Students), :rows => genders.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Age), :col2 => t(:Num_Students), :rows => ages.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Board_Position), :col2 => t(:Num_Students), :rows => board_positions.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Club_Position), :col2 => t(:Num_Students), :rows => club_positions.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Main_Interest), :col2 => t(:Num_Students), :rows => main_interests.to_a.sort, :total => total }
+ = render :partial => 'statistics_table', :locals => { :col1 => t(:Title), :col2 => t(:Num_Students), :rows => titles.to_a.sort, :total => total }
+
+
|
calmh/Register
|
8e60792a7a2300600e5a3857e34c53733e5fde02
|
Heavier performance test
|
diff --git a/test/performance/browsing_test.rb b/test/performance/browsing_test.rb
index 21cf3f0..ae3ad28 100644
--- a/test/performance/browsing_test.rb
+++ b/test/performance/browsing_test.rb
@@ -1,60 +1,61 @@
require 'test_helper'
require 'performance_test_help'
class BrowsingTest < ActionController::PerformanceTest
include Test::SetupOnce
def setup_fixtures; end
def teardown_fixtures; end
def self.setup_once
club = Factory(:club, :id => 150)
admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
%w[read edit delete graduations payments export].each do |perm|
Factory(:permission, :club => club, :user => admin, :permission => perm)
end
@@clubs = [ club ] + 10.times.map { Factory(:club) }
# Create many students, each with three graduations, payments, groups and mailing lists.
- grades = 3.times.map { Factory(:grade) }
- groups = 3.times.map { Factory(:group) }
- mailing_lists = 3.times.map { Factory(:mailing_list) }
+ grades = 10.times.map { Factory(:grade) }
+ groups = 10.times.map { Factory(:group) }
+ mailing_lists = 10.times.map { Factory(:mailing_list) }
@@clubs.each do |club|
- 100.times do
+ 100.times do |i|
+ index = i % 8
student = Factory(:student, :club => club)
- grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
- mailing_lists.each { |ml| student.mailing_lists << ml }
- groups.each { |ml| student.groups << ml }
+ grades[index..index+2].each { |grade| Factory(:graduation, :student => student, :grade => grade) }
+ mailing_lists[index..index+2].each { |ml| student.mailing_lists << ml }
+ groups[index..index+2].each { |ml| student.groups << ml }
3.times { Factory(:payment, :student => student) }
end
end
end
def setup
log_in_as_admin
end
def teardown
log_out
end
- def test_get_student_list
- visit "/clubs/150/students"
- assert_contain 'John Doe'
- end
+# def test_get_student_list
+# visit "/clubs/150/students"
+# assert_contain 'John Doe'
+# end
- def test_get_student_list_with_parameters
- visit "/clubs/150/students?c=name&d=up&gr=1&gi=1&ti=1&bp=1&cp=1&a=1"
- assert_contain 'John Doe'
- end
+# def test_get_student_list_with_parameters
+# visit "/clubs/150/students?c=name&d=up&gr=1&gi=1&ti=1&bp=1&cp=1&a=1"
+# assert_contain 'John Doe'
+# end
def test_search_all_students
visit "/students"
- assert_contain 'John Doe'
+ #assert_contain 'John Doe'
end
- def test_search_all_students_in_one_club
- visit "/students?ci[]=#{@@clubs[1].id}"
- assert_contain 'John Doe'
- end
+# def test_search_all_students_in_one_club
+# visit "/students?ci[]=#{@@clubs[1].id}"
+# assert_contain 'John Doe'
+# end
end
|
calmh/Register
|
34d849ceb983943bcce3c4306d61e9b9b8ffceb8
|
Heavier seed data
|
diff --git a/db/seeds.rb b/db/seeds.rb
index b7e414d..ea70e61 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,49 +1,51 @@
Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
admin = Factory(:administrator, :login => 'admin',
:password => 'admin', :password_confirmation => 'admin',
:groups_permission => true,
:mailinglists_permission => true,
:clubs_permission => true,
:users_permission => true,
:site_permission => true
)
# Create two clubs with a few basic students in
clubs = 2.times.map { Factory(:club) }
Factory(:student, :club => clubs[0], :email => "[email protected]", :password => "student", :password_confirmation => "student")
clubs.each do |club|
10.times do
Factory(:student, :club => club)
end
end
-# Create one club with a lot more students and data
-club = Factory(:club, :id => 150)
-clubs << club
-grades = 3.times.map { Factory(:grade) }
-groups = 3.times.map { Factory(:group) }
-mailing_lists = 3.times.map { Factory(:mailing_list) }
-150.times do
- student = Factory(:student, :club => club)
- grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
- mailing_lists.each { |ml| student.mailing_lists << ml }
- groups.each { |ml| student.groups << ml }
- 3.times { Factory(:payment, :student => student) }
+6.times do
+ # Create one club with a lot more students and data
+ club = Factory(:club)
+ clubs << club
+ grades = 3.times.map { Factory(:grade) }
+ groups = 3.times.map { Factory(:group) }
+ mailing_lists = 3.times.map { Factory(:mailing_list) }
+ 150.times do
+ student = Factory(:student, :club => club)
+ grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
+ mailing_lists.each { |ml| student.mailing_lists << ml }
+ groups.each { |ml| student.groups << ml }
+ 3.times { Factory(:payment, :student => student) }
+ end
end
%w[read edit delete graduations payments export].each do |perm|
clubs.each do |club|
Factory(:permission, :club => club, :user => admin, :permission => perm)
end
end
4.times do
Factory(:mailing_list)
end
4.times do
Factory(:group)
end
|
calmh/Register
|
2907235ac4b309eb8f5505d089e0567eeb31a11d
|
Eager load grade from student
|
diff --git a/app/models/student.rb b/app/models/student.rb
index 31f9941..0c4a596 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,163 +1,163 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
:conditions => conditions,
:include => [
- { :graduations => :grade_category },
+ { :graduations => [ :grade_category, :grade ] },
:payments, :club, :groups, :main_interest,
:board_position, :club_position, :title
]
}
}
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
@name ||= fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
@latest_payment ||= if !payments.blank?
payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
payment
end
end
def current_grade
@current_grade ||= calculate_current_grade
end
def calculate_current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
@active ||= if payments.blank?
Time.now - created_at < 86400 * 45
else
Time.now - payments[0].received < 86400 * 180
end
end
def gender=(value)
self[:gender] = value
@gender = nil
end
def gender
@gender ||= if personal_number =~ /-\d\d(\d)\d$/
$1.to_i.even? ? 'female' : 'male'
else
self[:gender] || 'unknown'
end
end
def age
@age ||= if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
((Date.today - date_of_birth) / 365.24).to_i
else
-1
end
end
def group_list
@group_list ||= groups.map{ |group| group.identifier }.join(", ")
end
end
|
calmh/Register
|
e1ceb5cf685de838f24fe8c75854ecefdc83dc30
|
Increase performance sligtly by caching operations on student.
|
diff --git a/app/models/student.rb b/app/models/student.rb
index 0c8b96f..31f9941 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,148 +1,163 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
- :conditions => conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
- } }
+ :conditions => conditions,
+ :include => [
+ { :graduations => :grade_category },
+ :payments, :club, :groups, :main_interest,
+ :board_position, :club_position, :title
+ ]
+ }
+ }
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
- return fname + " " + sname
+ @name ||= fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
- if !payments.blank?
- return payments[0]
+ @latest_payment ||= if !payments.blank?
+ payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
- return payment
+ payment
end
end
def current_grade
+ @current_grade ||= calculate_current_grade
+ end
+
+ def calculate_current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
- reference = Time.now
- if payments.blank?
- return reference - created_at < 86400 * 45
+ @active ||= if payments.blank?
+ Time.now - created_at < 86400 * 45
else
- return reference - payments[0].received < 86400 * 180
+ Time.now - payments[0].received < 86400 * 180
end
end
+ def gender=(value)
+ self[:gender] = value
+ @gender = nil
+ end
+
def gender
- if personal_number =~ /-\d\d(\d)\d$/
- return $1.to_i.even? ? 'female' : 'male'
+ @gender ||= if personal_number =~ /-\d\d(\d)\d$/
+ $1.to_i.even? ? 'female' : 'male'
+ else
+ self[:gender] || 'unknown'
end
- return self[:gender] || 'unknown'
end
def age
- if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
+ @age ||= if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
- return ((Date.today - date_of_birth) / 365.24).to_i
+ ((Date.today - date_of_birth) / 365.24).to_i
else
- return -1
+ -1
end
end
def group_list
- groups.map{ |group| group.identifier }.join(", ")
+ @group_list ||= groups.map{ |group| group.identifier }.join(", ")
end
end
|
calmh/Register
|
b10dff746a50c8d493a239cb3e6ee4cce8129a78
|
Fake Id to avoid warning.
|
diff --git a/app/models/message.rb b/app/models/message.rb
index f6d259a..4c9efaa 100644
--- a/app/models/message.rb
+++ b/app/models/message.rb
@@ -1,5 +1,7 @@
class Message
attr_accessor :from
attr_accessor :body
attr_accessor :subject
+
+ def id; 1; end
end
|
calmh/Register
|
f8caf81d7ef1cb94ad13c5034a53757f9f1850cb
|
First attempt att doing performance testing.
|
diff --git a/config/environments/performance.rb b/config/environments/performance.rb
new file mode 100644
index 0000000..f587ff7
--- /dev/null
+++ b/config/environments/performance.rb
@@ -0,0 +1,22 @@
+# Settings specified here will take precedence over those in config/environment.rb
+
+# The test environment is used exclusively to run your application's
+# test suite. You never need to work with it otherwise. Remember that
+# your test database is "scratch space" for the test suite and is wiped
+# and recreated between test runs. Don't rely on the data there!
+config.cache_classes = true
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = true
+
+# Disable request forgery protection in test environment
+config.action_controller.allow_forgery_protection = false
+
+# Tell Action Mailer not to deliver emails to the real world.
+# The :test delivery method accumulates sent emails in the
+# ActionMailer::Base.deliveries array.
+config.action_mailer.delivery_method = :test
diff --git a/db/seeds.rb b/db/seeds.rb
index a1fe9d0..b7e414d 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,33 +1,49 @@
Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
admin = Factory(:administrator, :login => 'admin',
:password => 'admin', :password_confirmation => 'admin',
:groups_permission => true,
:mailinglists_permission => true,
:clubs_permission => true,
:users_permission => true,
:site_permission => true
)
+# Create two clubs with a few basic students in
clubs = 2.times.map { Factory(:club) }
+Factory(:student, :club => clubs[0], :email => "[email protected]", :password => "student", :password_confirmation => "student")
clubs.each do |club|
10.times do
Factory(:student, :club => club)
end
end
-Factory(:student, :club => clubs[0], :email => "[email protected]", :password => "student", :password_confirmation => "student")
+
+# Create one club with a lot more students and data
+club = Factory(:club, :id => 150)
+clubs << club
+grades = 3.times.map { Factory(:grade) }
+groups = 3.times.map { Factory(:group) }
+mailing_lists = 3.times.map { Factory(:mailing_list) }
+150.times do
+ student = Factory(:student, :club => club)
+ grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
+ mailing_lists.each { |ml| student.mailing_lists << ml }
+ groups.each { |ml| student.groups << ml }
+ 3.times { Factory(:payment, :student => student) }
+end
+
%w[read edit delete graduations payments export].each do |perm|
clubs.each do |club|
Factory(:permission, :club => club, :user => admin, :permission => perm)
end
end
4.times do
Factory(:mailing_list)
end
4.times do
Factory(:group)
end
diff --git a/test/factories.rb b/test/factories.rb
index 60c9445..3979427 100644
--- a/test/factories.rb
+++ b/test/factories.rb
@@ -1,128 +1,132 @@
def cached_association(key)
object = key.to_s.camelize.constantize.first
object ||= Factory(key)
end
Factory.sequence :pnumber do |n|
- personal_number = '19800101-' + '%03d'%n
+ last = n % 1000; n /= 1000
+ day = (n % 28) + 1; n /= 28
+ month = (n % 12) + 1; n /= 12
+ year = 1980 + n
+ personal_number = "%4d%02d%02d-%03d"%[year, month, day, last]
# Calculate valid check digit
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..13].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
check = (10 - sum) % 10
personal_number + check.to_s
end
Factory.define :grade_category do |c|
c.sequence(:category) { |n| "Category #{n}" }
end
Factory.define :grade do |c|
c.sequence(:level) { |n| n }
c.description { |g| "Grade #{g.level}" }
end
Factory.define :graduation do |f|
f.instructor "Instructor"
f.examiner "Examiner"
f.graduated Time.now
f.grade { cached_association(:grade) }
f.grade_category { cached_association(:grade_category) }
f.student { cached_association(:grade) }
end
Factory.define :group do |f|
f.sequence(:identifier) { |n| "Group #{n}" }
f.comments "An auto-created group"
f.default 0
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :mailing_list do |f|
f.sequence(:email) { |n| "list#{n}@example.com" }
f.sequence(:description) { |n| "Mailing List #{n}" }
f.security "public"
f.default 0
end
Factory.define :mailing_lists_students do |f|
f.association :mailing_list
f.association :student
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :club do |c|
c.sequence(:name) {|n| "Club #{n}" }
end
Factory.define :board_position do |c|
c.position "Secretary"
end
Factory.define :club_position do |c|
c.position "Instructor"
end
Factory.define :title do |c|
c.title "Student"
c.level 1
end
Factory.define :payment do |c|
c.amount 700
c.received Time.now
c.description "Comment"
end
Factory.define :student do |s|
s.fname 'John'
s.sequence(:sname) {|n| "Doe_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) { |n| "person#{n}@example.com" }
s.personal_number { Factory.next(:pnumber) }
s.main_interest { cached_association(:grade_category) }
s.club { cached_association(:club) }
s.club_position { cached_association(:club_position) }
s.board_position { cached_association(:board_position) }
s.title { cached_association(:title) }
s.archived 0
end
Factory.define :administrator do |s|
s.fname 'Admin'
s.sequence(:sname) {|n| "Istrator_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "admin#{n}@example.com" }
s.sequence(:login) {|n| "admin#{n}" }
s.clubs_permission true
s.users_permission true
s.groups_permission true
s.mailinglists_permission true
s.site_permission true
end
Factory.define :permission do |p|
p.association :club
p.association :user, :factory => :administrator
p.permission "read"
end
Factory.define :configuration_setting do |o|
o.setting "setting"
o.value "value"
end
diff --git a/test/performance/browsing_test.rb b/test/performance/browsing_test.rb
index 4b60558..21cf3f0 100644
--- a/test/performance/browsing_test.rb
+++ b/test/performance/browsing_test.rb
@@ -1,9 +1,60 @@
require 'test_helper'
require 'performance_test_help'
-# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionController::PerformanceTest
- def test_homepage
- get '/'
+ include Test::SetupOnce
+
+ def setup_fixtures; end
+ def teardown_fixtures; end
+
+ def self.setup_once
+ club = Factory(:club, :id => 150)
+ admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
+ %w[read edit delete graduations payments export].each do |perm|
+ Factory(:permission, :club => club, :user => admin, :permission => perm)
+ end
+ @@clubs = [ club ] + 10.times.map { Factory(:club) }
+
+ # Create many students, each with three graduations, payments, groups and mailing lists.
+ grades = 3.times.map { Factory(:grade) }
+ groups = 3.times.map { Factory(:group) }
+ mailing_lists = 3.times.map { Factory(:mailing_list) }
+ @@clubs.each do |club|
+ 100.times do
+ student = Factory(:student, :club => club)
+ grades.each { |grade| Factory(:graduation, :student => student, :grade => grade) }
+ mailing_lists.each { |ml| student.mailing_lists << ml }
+ groups.each { |ml| student.groups << ml }
+ 3.times { Factory(:payment, :student => student) }
+ end
+ end
+ end
+
+ def setup
+ log_in_as_admin
+ end
+
+ def teardown
+ log_out
+ end
+
+ def test_get_student_list
+ visit "/clubs/150/students"
+ assert_contain 'John Doe'
+ end
+
+ def test_get_student_list_with_parameters
+ visit "/clubs/150/students?c=name&d=up&gr=1&gi=1&ti=1&bp=1&cp=1&a=1"
+ assert_contain 'John Doe'
+ end
+
+ def test_search_all_students
+ visit "/students"
+ assert_contain 'John Doe'
+ end
+
+ def test_search_all_students_in_one_club
+ visit "/students?ci[]=#{@@clubs[1].id}"
+ assert_contain 'John Doe'
end
end
diff --git a/test/setup_once.rb b/test/setup_once.rb
new file mode 100644
index 0000000..d496776
--- /dev/null
+++ b/test/setup_once.rb
@@ -0,0 +1,25 @@
+require 'test/unit'
+
+module Test::SetupOnce
+ module ClassMethods
+ def setup_once; end
+ def teardown_once; end
+
+ def suite
+ returning super do |suite|
+ suite.send(:instance_variable_set, :@_test_klazz, self)
+ suite.instance_eval do
+ def run(*args)
+ @_test_klazz.setup_once
+ super
+ @_test_klazz.teardown_once
+ end
+ end
+ end
+ end
+ end
+
+ def self.included(test)
+ test.extend(ClassMethods)
+ end
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 29ea377..f3d9c70 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,61 +1,42 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
+require 'setup_once'
require 'test_help'
-#require 'authlogic/test_case'
require "webrat"
- Webrat.configure do |config|
- config.mode = :rails
- end
+Webrat.configure do |config|
+ config.mode = :rails
+end
class ActiveSupport::TestCase
# setup :activate_authlogic
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
- # Every Active Record database supports transactions except MyISAM tables
- # in MySQL. Turn off transactional fixtures in this case; however, if you
- # don't care one way or the other, switching from MyISAM to InnoDB tables
- # is recommended.
- #
- # The only drawback to using transactional fixtures is when you actually
- # need to test transactions. Since your test is bracketed by a transaction,
- # any transactions started in your code will be automatically rolled back.
- self.use_transactional_fixtures = true
-
- # Instantiated fixtures are slow, but give you @david where otherwise you
- # would need people(:david). If you don't want to migrate your existing
- # test cases which use the @david style and don't mind the speed hit (each
- # instantiated fixtures translates to a database query per test method),
- # then set this back to true.
- self.use_instantiated_fixtures = false
-
- # Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
- #
- # Note: You'll currently still have to declare fixtures explicitly in integration tests
- # -- they do not yet inherit this setting
- fixtures :all
-
- # Add more helper methods to be used by all tests here...
def create_club_and_admin
- @club = Factory(:club)
- @admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
- %w[read edit delete graduations payments export].each do |perm|
- Factory(:permission, :club => @club, :user => @admin, :permission => perm)
+ @club = Factory(:club)
+ @admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
+ %w[read edit delete graduations payments export].each do |perm|
+ Factory(:permission, :club => @club, :user => @admin, :permission => perm)
end
end
def log_in_as_admin
- visit "/?locale=en"
- fill_in "Login", :with => "admin"
- fill_in "Password", :with => "admin"
- uncheck "Remember me"
- click_button "Log in"
+ visit "/?locale=en"
+ fill_in "Login", :with => "admin"
+ fill_in "Password", :with => "admin"
+ uncheck "Remember me"
+ click_button "Log in"
+ end
+
+ def log_out
+ visit "/?locale=en"
+ click_link "Log out"
end
end
|
calmh/Register
|
749d98abdc73b569dbe240db964108059ba599fa
|
These two cannot be the same array...
|
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index 89430fe..15fdc82 100644
--- a/app/controllers/messages_controller.rb
+++ b/app/controllers/messages_controller.rb
@@ -1,31 +1,32 @@
class MessagesController < ApplicationController
def new
@students = Student.find(session[:selected_students]);
@message = Message.new
@message.from = current_user.email
@message.subject = get_default(:message_subject)
@message.body = get_default(:message_body)
end
def update
@message = Message.new
@message.from = current_user.email
@message.body = params[:message][:body]
@message.subject = params[:message][:subject]
@students = Student.find(session[:selected_students])
session[:selected_students] = nil
- @sent = @noemail = []
+ @sent = []
+ @noemail = []
@students.each do |student|
if student.email.blank?
@noemail << student
else
student.deliver_generic_message!(@message)
@sent << student
end
end
set_default(:message_subject, @message.subject)
set_default(:message_body, @message.body)
end
end
|
calmh/Register
|
e9e7029738208c5ecd7aa48ecd311c74584bef47
|
Fix microbug in message sending.
|
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index 93629b1..89430fe 100644
--- a/app/controllers/messages_controller.rb
+++ b/app/controllers/messages_controller.rb
@@ -1,31 +1,31 @@
class MessagesController < ApplicationController
def new
@students = Student.find(session[:selected_students]);
@message = Message.new
@message.from = current_user.email
@message.subject = get_default(:message_subject)
@message.body = get_default(:message_body)
end
def update
@message = Message.new
@message.from = current_user.email
@message.body = params[:message][:body]
@message.subject = params[:message][:subject]
@students = Student.find(session[:selected_students])
session[:selected_students] = nil
@sent = @noemail = []
@students.each do |student|
if student.email.blank?
- @noemail << s
+ @noemail << student
else
student.deliver_generic_message!(@message)
@sent << student
end
end
set_default(:message_subject, @message.subject)
set_default(:message_body, @message.body)
end
end
|
calmh/Register
|
56002c0dbb0c818375799aa2800b32562366cf84
|
Fix problem with sending message.
|
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index 9594688..93629b1 100644
--- a/app/controllers/messages_controller.rb
+++ b/app/controllers/messages_controller.rb
@@ -1,25 +1,31 @@
class MessagesController < ApplicationController
def new
- @message = Message.new(:from => current_user.email, :subject => get_default(:message_subject), :body => get_default(:message_body))
@students = Student.find(session[:selected_students]);
+ @message = Message.new
+ @message.from = current_user.email
+ @message.subject = get_default(:message_subject)
+ @message.body = get_default(:message_body)
end
def update
- @message = Message.new(:from => current_user.email, :body => params[:message][:body], :subject => params[:message][:subject])
+ @message = Message.new
+ @message.from = current_user.email
+ @message.body = params[:message][:body]
+ @message.subject = params[:message][:subject]
@students = Student.find(session[:selected_students])
session[:selected_students] = nil
@sent = @noemail = []
@students.each do |student|
if student.email.blank?
@noemail << s
else
student.deliver_generic_message!(@message)
@sent << student
end
end
set_default(:message_subject, @message.subject)
set_default(:message_body, @message.body)
end
end
diff --git a/test/integration/messages_test.rb b/test/integration/messages_test.rb
new file mode 100644
index 0000000..77602b7
--- /dev/null
+++ b/test/integration/messages_test.rb
@@ -0,0 +1,22 @@
+require 'test_helper'
+
+class MessagesTest < ActionController::IntegrationTest
+ def setup
+ create_club_and_admin
+
+ @students = 5.times.map { Factory(:student, :club => @club) }
+ end
+
+test "should send message to multiple students" do
+ log_in_as_admin
+ click_link @club.name
+
+ @students[0..3].each do |s|
+ check "selected_students_#{s.id}"
+ end
+ click_button "Send message"
+ fill_in "Subject", :with => "Test subject"
+ fill_in "Body", :with => "Test body"
+ click_button "Send"
+end
+end
|
calmh/Register
|
c256ab21f709679d557c64fe4d4b5391aef72445
|
Fix problem with leakage between clubs.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 85a2b23..a58344c 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,320 +1,320 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
- conditions = []
+ conditions = [ "archived = 0" ]
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def archive
@student = Student.find(params[:id])
@student.archived = 1
@student.save
redirect_to(@student.club)
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to]
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
ml_ids = ml_ids.keys.select do |x|
if cur_ids.include?(x)
true
next
end
ml = MailingList.find(x)
ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index 35952e7..0c8b96f 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,148 +1,148 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
- :conditions => [ "archived = 0" ] + conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
+ :conditions => conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
} }
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
return payment
end
end
def current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
reference = Time.now
if payments.blank?
return reference - created_at < 86400 * 45
else
return reference - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] || 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today - date_of_birth) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |group| group.identifier }.join(", ")
end
end
diff --git a/db/seeds.rb b/db/seeds.rb
index 0def704..a1fe9d0 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,29 +1,33 @@
Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
admin = Factory(:administrator, :login => 'admin',
:password => 'admin', :password_confirmation => 'admin',
:groups_permission => true,
:mailinglists_permission => true,
:clubs_permission => true,
:users_permission => true,
:site_permission => true
)
-club = Factory(:club)
-10.times do
- Factory(:student, :club => club)
+clubs = 2.times.map { Factory(:club) }
+clubs.each do |club|
+ 10.times do
+ Factory(:student, :club => club)
+ end
end
-Factory(:student, :club => club, :email => "[email protected]", :password => "student", :password_confirmation => "student")
+Factory(:student, :club => clubs[0], :email => "[email protected]", :password => "student", :password_confirmation => "student")
%w[read edit delete graduations payments export].each do |perm|
- Factory(:permission, :club => club, :user => admin, :permission => perm)
+ clubs.each do |club|
+ Factory(:permission, :club => club, :user => admin, :permission => perm)
+ end
end
4.times do
Factory(:mailing_list)
end
4.times do
Factory(:group)
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index 1941d87..c193f8f 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,247 +1,263 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
test "student page should show all students" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
assert_contain " #{@students.length} students"
end
+ test "student page should show only this club's students" do
+ other_club = Factory(:club)
+ other_students = 10.times.map { Factory(:student, :club => other_club )}
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ @students.each do |s|
+ assert_contain s.name
+ end
+ other_students.each do |s|
+ assert_not_contain s.name
+ end
+ assert_contain " #{@students.length} students"
+ end
+
test "student page should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
archived_students.each do |s|
assert_not_contain s.name
end
assert_contain " #{@students.length} students"
end
test "overview page student count should not include archived students" do
archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
log_in_as_admin
click_link "Clubs"
assert_contain Regexp.new("\\b#{@students.length}\\b")
assert_not_contain Regexp.new("\\b#{@students.length + archived_students.length}\\b")
end
test "student should be archived and then not be listed on the club page" do
archived = @students[0]
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link archived.name
click_link "Edit"
click_link "Archive"
click_link @club.name
assert_not_contain archived.name
end
test "should not create new blank student" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
click_button "Save"
assert_not_contain "created"
assert_contain "can't be blank"
end
test "should create new student with minimal info" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
select @category.category
click_button "Save"
assert_contain "created"
end
test "should create a new student in x groups" do
@admin.groups_permission = true
@admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_groups.each do |g|
check g.identifier
end
click_button "Save"
assert_contain "created"
member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_contain "Test Testsson"
end
non_member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_not_contain "Test Testsson"
end
end
test "should create a new student in x mailing lists" do
@admin.mailinglists_permission = true
@admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_lists.each do |m|
check m.description
end
click_button "Save"
assert_contain "created"
member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_contain "Test Testsson"
end
non_member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_not_contain "Test Testsson"
end
end
test "new student should join club mailing list per default" do
mailing_list = Factory(:mailing_list, :default => 1)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
other_club = Factory(:club)
mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_not_contain "Test Testsson"
end
test "student should be able to edit self without losing groups" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
group = Factory(:group)
student.groups << group;
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.groups.length == 1
end
test "student should join mailing list" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_list = Factory(:mailing_list)
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_list.description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == [ mailing_list.id ]
end
test "student should join one mailing list and leave another" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
end
end
|
calmh/Register
|
e1dc6cbe793b36b49ff4cc543868bc4145c09677
|
Add default value to archived column.
|
diff --git a/db/migrate/20100307204058_add_archived_to_user.rb b/db/migrate/20100307204058_add_archived_to_user.rb
index f8cf0c9..c32fdf2 100644
--- a/db/migrate/20100307204058_add_archived_to_user.rb
+++ b/db/migrate/20100307204058_add_archived_to_user.rb
@@ -1,9 +1,9 @@
class AddArchivedToUser < ActiveRecord::Migration
def self.up
- add_column :users, :archived, :integer
+ add_column :users, :archived, :integer, :default => 0
end
def self.down
remove_column :users, :archived
end
end
diff --git a/db/schema.rb b/db/schema.rb
index 3d4f934..0e451c9 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,181 +1,181 @@
# 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 => 20100307204058) do
create_table "board_positions", :force => true do |t|
t.string "position"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "club_positions", :force => true do |t|
t.string "position"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "clubs", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "configuration_settings", :force => true do |t|
t.string "setting"
t.string "value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "configuration_settings", ["setting"], :name => "index_configuration_settings_on_setting"
create_table "default_values", :force => true do |t|
t.integer "user_id"
t.string "key"
t.string "value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "default_values", ["key"], :name => "index_default_values_on_key"
create_table "grade_categories", :force => true do |t|
t.string "category"
end
create_table "grades", :force => true do |t|
t.string "description"
t.integer "level"
end
create_table "graduations", :force => true do |t|
t.integer "student_id"
t.string "instructor"
t.string "examiner"
t.datetime "graduated"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "grade_id"
t.integer "grade_category_id"
end
add_index "graduations", ["student_id"], :name => "index_graduations_on_student_id"
create_table "groups", :force => true do |t|
t.string "identifier"
t.text "comments"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "default"
end
create_table "groups_students", :id => false, :force => true do |t|
t.integer "group_id"
t.integer "student_id"
end
add_index "groups_students", ["group_id"], :name => "index_groups_students_on_group_id"
add_index "groups_students", ["student_id"], :name => "index_groups_students_on_student_id"
create_table "mailing_lists", :force => true do |t|
t.string "email"
t.string "description"
t.string "security"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "default"
t.integer "club_id"
end
create_table "mailing_lists_students", :id => false, :force => true do |t|
t.integer "mailing_list_id"
t.integer "student_id"
end
add_index "mailing_lists_students", ["mailing_list_id"], :name => "index_mailing_lists_students_on_mailing_list_id"
add_index "mailing_lists_students", ["student_id"], :name => "index_mailing_lists_students_on_student_id"
create_table "payments", :force => true do |t|
t.integer "student_id"
t.float "amount"
t.datetime "received"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "payments", ["student_id"], :name => "index_payments_on_student_id"
create_table "permissions", :force => true do |t|
t.integer "club_id"
t.integer "user_id"
t.string "permission"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "permissions", ["club_id"], :name => "index_permissions_on_club_id"
add_index "permissions", ["user_id"], :name => "index_permissions_on_user_id"
create_table "titles", :force => true do |t|
t.string "title"
t.integer "level"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "sname"
t.string "fname"
t.string "email"
t.string "crypted_password"
t.datetime "created_at"
t.datetime "updated_at"
t.string "persistence_token"
t.string "single_access_token"
t.string "perishable_token"
t.integer "login_count"
t.integer "failed_login_count"
t.datetime "last_request_at"
t.datetime "current_login_at"
t.datetime "last_login_at"
t.string "current_login_ip"
t.string "last_login_ip"
t.integer "users_permission"
t.integer "groups_permission"
t.integer "mailinglists_permission"
t.integer "clubs_permission"
t.integer "site_permission"
t.string "type"
t.integer "club_id"
t.string "personal_number"
t.string "home_phone"
t.string "mobile_phone"
t.string "street"
t.string "zipcode"
t.string "city"
t.text "comments"
t.string "gender"
t.integer "main_interest_id"
t.integer "title_id"
t.integer "board_position_id"
t.integer "club_position_id"
- t.integer "archived"
+ t.integer "archived", :default => 0
end
add_index "users", ["club_id"], :name => "index_users_on_club_id"
add_index "users", ["fname"], :name => "index_users_on_fname"
add_index "users", ["sname"], :name => "index_users_on_sname"
add_index "users", ["type"], :name => "index_users_on_type"
end
|
calmh/Register
|
fbd5481fa8e2c49b7533f967852f452fa97bf5ba
|
Add forgotten migration.
|
diff --git a/db/migrate/20100307204058_add_archived_to_user.rb b/db/migrate/20100307204058_add_archived_to_user.rb
new file mode 100644
index 0000000..f8cf0c9
--- /dev/null
+++ b/db/migrate/20100307204058_add_archived_to_user.rb
@@ -0,0 +1,9 @@
+class AddArchivedToUser < ActiveRecord::Migration
+ def self.up
+ add_column :users, :archived, :integer
+ end
+
+ def self.down
+ remove_column :users, :archived
+ end
+end
|
calmh/Register
|
eb119081b10264c4ad933706229d31e72395ff05
|
Add archived field to students.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 194ac7d..85a2b23 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,313 +1,320 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = []
if !@club_id.nil?
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
else
conditions << "club_id = ?"
end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
# TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
+ def archive
+ @student = Student.find(params[:id])
+ @student.archived = 1
+ @student.save
+ redirect_to(@student.club)
+ end
+
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to]
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
ml_ids = ml_ids.keys.select do |x|
if cur_ids.include?(x)
true
next
end
ml = MailingList.find(x)
ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
diff --git a/app/helpers/clubs_helper.rb b/app/helpers/clubs_helper.rb
index 2180733..bdb4c06 100644
--- a/app/helpers/clubs_helper.rb
+++ b/app/helpers/clubs_helper.rb
@@ -1,6 +1,6 @@
module ClubsHelper
def num_students(club)
- return club.students.length if !club.students.blank?
+ return club.students.not_archived.length if !club.students.blank?
return 0
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index 852e62e..35952e7 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,147 +1,148 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
:if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
+ named_scope :not_archived, :conditions => { :archived => 0 }
named_scope :all_inclusive, lambda { |conditions| {
- :conditions => conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
+ :conditions => [ "archived = 0" ] + conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
} }
acts_as_authentic do |config|
config.validate_password_field = true
config.require_password_confirmation = true
config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
(digit.to_i * fact).to_s.split(//).each do |fact_digit|
sum += fact_digit.to_i
end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
payment = Payment.new
payment.amount = 0
payment.received = created_at
payment.description = "Start"
return payment
end
end
def current_grade
my_graduations = self.graduations
if my_graduations.blank?
return nil
else
in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return my_graduations[0]
end
end
end
def active?
reference = Time.now
if payments.blank?
return reference - created_at < 86400 * 45
else
return reference - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] || 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today - date_of_birth) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |group| group.identifier }.join(", ")
end
end
diff --git a/app/views/students/_form.html.haml b/app/views/students/_form.html.haml
index 5746023..f2e8d02 100644
--- a/app/views/students/_form.html.haml
+++ b/app/views/students/_form.html.haml
@@ -1,103 +1,105 @@
= f.hidden_field :club_id, :class => 'text_field'
.group
%label.label= t(:Groups)
- groups.each do |group|
= check_box_tag "member_of[" + group.id.to_s + "]", value = "1", checked = @student.group_ids.include?(group.id), :class => 'checkbox'
%label{ :for => "member_of_" + group.id.to_s }= group.identifier
%br
.group
= f.label :fname, t(:Fname), :class => :label
= f.text_field :fname, :class => 'text_field'
.group
= f.label :sname, t(:Sname), :class => :label
= f.text_field :sname, :class => 'text_field'
.group
= f.label :personal_number, t(:Personal_Num), :class => :label
= f.text_field :personal_number, :class => 'text_field'
%span.description= t(:Personal_Num_descr)
.group
= f.label :gender, t(:Gender), :class => :label
= select "student", "gender", ['male', 'female', 'unknown'].map { |g| [ t(g).titlecase, g ] }
%br
%span.description= t(:Gender_descr)
.group
= f.label :main_interest_id, t(:Main_Interest), :class => :label
= select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] }
%br
.group
= f.label :email, t(:Email), :class => :label
= f.text_field :email, :class => 'text_field'
.group
%label.label= t(:Mailing_Lists)
- mailing_lists.each do |ml|
- if ml.club == nil || ml.club == @club
= check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id), :class => 'checkbox'
%label{ :for => "subscribes_to_" + ml.id.to_s }= ml.description
%br
.group
= f.label :home_phone, t(:Home_phone), :class => :label
= f.text_field :home_phone, :class => 'text_field'
%span.description= t(:Phone_number_descr)
.group
= f.label :mobile_phone, t(:Mobile_phone), :class => :label
= f.text_field :mobile_phone, :class => 'text_field'
%span.description= t(:Phone_number_descr)
.group
= f.label :street, t(:Street), :class => :label
= f.text_field :street, :class => 'text_field'
.group
= f.label :zipcode, t(:Zipcode), :class => :label
= f.text_field :zipcode, :class => 'text_field'
.group
= f.label :city, t(:City), :class => :label
= f.text_field :city, :class => 'text_field'
.group
= f.label :title_id, t(:Title), :class => :label
= select "student", "title_id", titles.map { |g| [ g.title, g.id ] }
%br
.group
= f.label :club_position_id, t(:Club_Position), :class => :label
= select "student", "club_position_id", club_positions.map { |g| [ g.position, g.id ] }
%br
.group
= f.label :board_position_id, t(:Board_Position), :class => :label
= select "student", "board_position_id", board_positions.map { |g| [ g.position, g.id ] }
%br
.group
= f.label :comments, t(:Comments), :class => :label
= f.text_area :comments, :class => 'text_area', :rows => 4, :cols => 16
.group
= f.label :password, t(:New_Password), :class => :label
= f.password_field :password, :class => 'text_field'
%span.description= t(:New_Password_descr)
.group
= f.label :password_confirmation, t(:Confirm_Password), :class => :label
= f.password_field :password_confirmation, :class => 'text_field'
.group.navform
%input.button{ :type => 'submit', :value => t(:Save) + " →" }
- if controller.action_name != "new" && controller.action_name != "create"
+ = t(:or)
+ = link_to t(:Archive), archive_student_path(@student), :confirm => t(:Are_you_sure_archive)
- if current_user.delete_permission?(@club)
= t(:or)
= link_to t(:Destroy), @student, :confirm => t(:Are_you_sure_student), :method => :delete
= t(:or)
= link_to t(:Cancel), student_path(@student)
diff --git a/config/locales/en.yml b/config/locales/en.yml
index df57302..fb0e6f4 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,209 +1,211 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
- Are_you_sure_club: Are you sure? The will club be deleted.
+ Are_you_sure_club: Are you sure? The club will be deleted.
+ Are_you_sure_archive: Are you sure? The student will be archived, and thus hidden from view until unarchived.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
Welcome_Text: Welcome Text
Welcome_Text_descr: "This is the text that is sent in the welcome email. Use the placeholders %club%, %url% and %password% to denote the current club, URL to log in at and the user's password.."
+ Archive: Archive
activerecord:
messages:
in_future: in the future
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index e0a8e4d..8658674 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,284 +1,286 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
+ Are_you_sure_archive: Ãr du säker? Eleven kommer att arkiveras, och därmed vara dold tills han/hon aktiveras igen.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
Body_text: Brödtext
Send: Skicka
Subject: Ãrende
From: Från
Back: Tillbaka
Message_sent_to: Meddelandet skickades till
Couldnt_send_to: Kunde inte skicka meddelande till
because_no_email: eftersom de inte har en epostadress.
Welcome_Text: Välkomsttext
Welcome_Text_descr: "Detta är den text som skickas ut i välkomstbrevet. Använd platshållarna %club%, %url% och %password% för att hänvisa till den aktuella klubben, URL:en att logga in på samt användarens lösenord."
+ Archive: Arkivera
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
in_future: i framtiden
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/config/routes.rb b/config/routes.rb
index 81cec72..d6fe5c1 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,81 +1,81 @@
ActionController::Routing::Routes.draw do |map|
# For debugging, check validations
map.validate 'validate', :controller => 'application', :action => 'validate'
map.edit_site 'edit_site_settings', :controller => 'application', :action => 'edit_site_settings'
map.update_site 'update_site_settings', :controller => 'application', :action => 'update_site_settings'
# Bulk operations
map.connect 'students/bulkoperations', :controller => 'students', :action => 'bulk_operations'
map.connect 'graduations/new_bulk', :controller => 'graduations', :action => 'new_bulk'
map.connect 'graduations/update_bulk', :controller => 'graduations', :action => 'update_bulk'
map.connect 'payments/new_bulk', :controller => 'payments', :action => 'new_bulk'
map.connect 'payments/update_bulk', :controller => 'payments', :action => 'update_bulk'
# Clubs, students and subresources
map.resources :clubs, :shallow => true do |club|
- club.resources :students, :collection => { :filter => :post } do |student|
+ club.resources :students, :collection => { :filter => :post }, :member => { :archive => :get } do |student|
student.resources :payments
student.resources :graduations
end
end
map.resources :students, :only => :index
# Other singular resources
map.resources :administrators
map.resources :groups
map.resources :mailing_lists
map.resources :messages
# For login and logout
map.resource :user_session
# Password reset
map.resources :password_resets
# Display club list at /
map.root :controller => :clubs
# map.root :controller => "user_sessions", :action => "new"
# 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/schema.rb b/db/schema.rb
index 5ecde1a..3d4f934 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,180 +1,181 @@
# 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 => 20100124102924) do
+ActiveRecord::Schema.define(:version => 20100307204058) do
create_table "board_positions", :force => true do |t|
t.string "position"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "club_positions", :force => true do |t|
t.string "position"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "clubs", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "configuration_settings", :force => true do |t|
t.string "setting"
t.string "value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "configuration_settings", ["setting"], :name => "index_configuration_settings_on_setting"
create_table "default_values", :force => true do |t|
t.integer "user_id"
t.string "key"
t.string "value"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "default_values", ["key"], :name => "index_default_values_on_key"
create_table "grade_categories", :force => true do |t|
t.string "category"
end
create_table "grades", :force => true do |t|
t.string "description"
t.integer "level"
end
create_table "graduations", :force => true do |t|
t.integer "student_id"
t.string "instructor"
t.string "examiner"
t.datetime "graduated"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "grade_id"
t.integer "grade_category_id"
end
add_index "graduations", ["student_id"], :name => "index_graduations_on_student_id"
create_table "groups", :force => true do |t|
t.string "identifier"
t.text "comments"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "default"
end
create_table "groups_students", :id => false, :force => true do |t|
t.integer "group_id"
t.integer "student_id"
end
add_index "groups_students", ["group_id"], :name => "index_groups_students_on_group_id"
add_index "groups_students", ["student_id"], :name => "index_groups_students_on_student_id"
create_table "mailing_lists", :force => true do |t|
t.string "email"
t.string "description"
t.string "security"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "default"
t.integer "club_id"
end
create_table "mailing_lists_students", :id => false, :force => true do |t|
t.integer "mailing_list_id"
t.integer "student_id"
end
add_index "mailing_lists_students", ["mailing_list_id"], :name => "index_mailing_lists_students_on_mailing_list_id"
add_index "mailing_lists_students", ["student_id"], :name => "index_mailing_lists_students_on_student_id"
create_table "payments", :force => true do |t|
t.integer "student_id"
t.float "amount"
t.datetime "received"
t.string "description"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "payments", ["student_id"], :name => "index_payments_on_student_id"
create_table "permissions", :force => true do |t|
t.integer "club_id"
t.integer "user_id"
t.string "permission"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "permissions", ["club_id"], :name => "index_permissions_on_club_id"
add_index "permissions", ["user_id"], :name => "index_permissions_on_user_id"
create_table "titles", :force => true do |t|
t.string "title"
t.integer "level"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "sname"
t.string "fname"
t.string "email"
t.string "crypted_password"
t.datetime "created_at"
t.datetime "updated_at"
t.string "persistence_token"
t.string "single_access_token"
t.string "perishable_token"
t.integer "login_count"
t.integer "failed_login_count"
t.datetime "last_request_at"
t.datetime "current_login_at"
t.datetime "last_login_at"
t.string "current_login_ip"
t.string "last_login_ip"
t.integer "users_permission"
t.integer "groups_permission"
t.integer "mailinglists_permission"
t.integer "clubs_permission"
t.integer "site_permission"
t.string "type"
t.integer "club_id"
t.string "personal_number"
t.string "home_phone"
t.string "mobile_phone"
t.string "street"
t.string "zipcode"
t.string "city"
t.text "comments"
t.string "gender"
t.integer "main_interest_id"
t.integer "title_id"
t.integer "board_position_id"
t.integer "club_position_id"
+ t.integer "archived"
end
add_index "users", ["club_id"], :name => "index_users_on_club_id"
add_index "users", ["fname"], :name => "index_users_on_fname"
add_index "users", ["sname"], :name => "index_users_on_sname"
add_index "users", ["type"], :name => "index_users_on_type"
end
diff --git a/test/factories.rb b/test/factories.rb
index f566d8f..60c9445 100644
--- a/test/factories.rb
+++ b/test/factories.rb
@@ -1,127 +1,128 @@
def cached_association(key)
object = key.to_s.camelize.constantize.first
object ||= Factory(key)
end
Factory.sequence :pnumber do |n|
personal_number = '19800101-' + '%03d'%n
# Calculate valid check digit
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..13].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
check = (10 - sum) % 10
personal_number + check.to_s
end
Factory.define :grade_category do |c|
c.sequence(:category) { |n| "Category #{n}" }
end
Factory.define :grade do |c|
c.sequence(:level) { |n| n }
c.description { |g| "Grade #{g.level}" }
end
Factory.define :graduation do |f|
f.instructor "Instructor"
f.examiner "Examiner"
f.graduated Time.now
f.grade { cached_association(:grade) }
f.grade_category { cached_association(:grade_category) }
f.student { cached_association(:grade) }
end
Factory.define :group do |f|
f.sequence(:identifier) { |n| "Group #{n}" }
f.comments "An auto-created group"
f.default 0
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :mailing_list do |f|
f.sequence(:email) { |n| "list#{n}@example.com" }
f.sequence(:description) { |n| "Mailing List #{n}" }
f.security "public"
f.default 0
end
Factory.define :mailing_lists_students do |f|
f.association :mailing_list
f.association :student
end
Factory.define :groups_students do |f|
f.association :group
f.association :student
end
Factory.define :club do |c|
c.sequence(:name) {|n| "Club #{n}" }
end
Factory.define :board_position do |c|
c.position "Secretary"
end
Factory.define :club_position do |c|
c.position "Instructor"
end
Factory.define :title do |c|
c.title "Student"
c.level 1
end
Factory.define :payment do |c|
c.amount 700
c.received Time.now
c.description "Comment"
end
Factory.define :student do |s|
s.fname 'John'
s.sequence(:sname) {|n| "Doe_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) { |n| "person#{n}@example.com" }
s.personal_number { Factory.next(:pnumber) }
s.main_interest { cached_association(:grade_category) }
s.club { cached_association(:club) }
s.club_position { cached_association(:club_position) }
s.board_position { cached_association(:board_position) }
s.title { cached_association(:title) }
+ s.archived 0
end
Factory.define :administrator do |s|
s.fname 'Admin'
s.sequence(:sname) {|n| "Istrator_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "admin#{n}@example.com" }
s.sequence(:login) {|n| "admin#{n}" }
s.clubs_permission true
s.users_permission true
s.groups_permission true
s.mailinglists_permission true
s.site_permission true
end
Factory.define :permission do |p|
p.association :club
p.association :user, :factory => :administrator
p.permission "read"
end
Factory.define :configuration_setting do |o|
o.setting "setting"
o.value "value"
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index ccecf95..1941d87 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,210 +1,247 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
test "student page should show all students" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
assert_contain " #{@students.length} students"
end
+ test "student page should not include archived students" do
+ archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ @students.each do |s|
+ assert_contain s.name
+ end
+ archived_students.each do |s|
+ assert_not_contain s.name
+ end
+ assert_contain " #{@students.length} students"
+ end
+
+ test "overview page student count should not include archived students" do
+ archived_students = 10.times.map { Factory(:student, :club => @club, :archived => 1) }
+
+ log_in_as_admin
+ click_link "Clubs"
+ assert_contain Regexp.new("\\b#{@students.length}\\b")
+ assert_not_contain Regexp.new("\\b#{@students.length + archived_students.length}\\b")
+ end
+
+ test "student should be archived and then not be listed on the club page" do
+ archived = @students[0]
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link archived.name
+ click_link "Edit"
+ click_link "Archive"
+
+ click_link @club.name
+ assert_not_contain archived.name
+ end
+
test "should not create new blank student" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
click_button "Save"
assert_not_contain "created"
assert_contain "can't be blank"
end
test "should create new student with minimal info" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
select @category.category
click_button "Save"
assert_contain "created"
end
test "should create a new student in x groups" do
@admin.groups_permission = true
@admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_groups.each do |g|
check g.identifier
end
click_button "Save"
assert_contain "created"
member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_contain "Test Testsson"
end
non_member_groups.each do |g|
click_link "Groups"
click_link g.identifier
assert_not_contain "Test Testsson"
end
end
test "should create a new student in x mailing lists" do
@admin.mailinglists_permission = true
@admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
member_lists.each do |m|
check m.description
end
click_button "Save"
assert_contain "created"
member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_contain "Test Testsson"
end
non_member_lists.each do |m|
click_link "Mailing Lists"
click_link m.email
assert_not_contain "Test Testsson"
end
end
test "new student should join club mailing list per default" do
mailing_list = Factory(:mailing_list, :default => 1)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
other_club = Factory(:club)
mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
@admin.mailinglists_permission = true
@admin.save
log_in_as_admin
click_link "Clubs"
click_link @club.name
click_link "New student"
fill_in "Name", :with => "Test"
fill_in "Surname", :with => "Testsson"
fill_in "Personal number", :with => "19850203"
click_button "Save"
click_link "Mailing Lists"
click_link mailing_list.email
assert_not_contain "Test Testsson"
end
test "student should be able to edit self without losing groups" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
group = Factory(:group)
student.groups << group;
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.groups.length == 1
end
test "student should join mailing list" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_list = Factory(:mailing_list)
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_list.description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids == [ mailing_list.id ]
end
test "student should join one mailing list and leave another" do
student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
mailing_lists = 2.times.map { Factory(:mailing_list) }
student.mailing_lists << mailing_lists[1]
student.save!
visit "/?locale=en"
fill_in "Login", :with => student.email
fill_in "Password", :with => "password"
click_button "Log in"
check mailing_lists[0].description
uncheck mailing_lists[1].description
click_button "Save"
student_from_db = Student.find(student.id)
assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
end
end
|
calmh/Register
|
ad7efc4206887d17365fb607b6be931fc8a2f95d
|
Add welcome text editor to site settings. Fix bug with site settings saving.
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 135df2e..cc62e7d 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,166 +1,174 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class SiteSettings
- def self.get_setting(setting)
- setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
+ def self.get_setting(setting_name)
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
return "" if setting == nil
return setting.value
end
- def self.set_setting(setting, value)
- setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
+ def self.set_setting(setting_name, value)
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting_name })
if setting == nil
setting = ConfigurationSetting.new
- setting.setting = setting
+ setting.setting = setting_name
end
- s.value = value
- s.save!
+ setting.value = value
+ setting.save!
end
def self.site_name
get_setting(:site_name)
end
def self.site_name=(value)
set_setting(:site_name, value)
end
def self.site_theme
get_setting(:site_theme)
end
def self.site_theme=(value)
set_setting(:site_theme, value)
end
+
+ def self.welcome_text
+ get_setting(:welcome_text)
+ end
+ def self.welcome_text=(value)
+ set_setting(:welcome_text, value)
+ end
end
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user
before_filter :set_locale
protect_from_forgery # :secret => '4250e2ff2a2308b6668755ef76677cbb'
before_filter :require_site_permission, :only => [ :edit_site_settings, :update_site_settings ]
def set_locale
session[:locale] = params[:locale] if params[:locale] != nil
I18n.locale = session[:locale] if session[:locale] != nil
end
def edit_site_settings
@available_themes = Dir.entries("public/stylesheets/themes").select { |entry| !entry.starts_with? '.' }.sort
end
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
+ SiteSettings.welcome_text = params[:welcome_text]
expire_fragment('layout_header')
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
def validate
require_administrator end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def denied
store_location
flash[:warning] = t(:Must_log_in)
current_user_session.destroy if current_user_session
redirect_to new_user_session_path
return false
end
def require_student_or_administrator
return denied unless current_user
return true
end
def require_administrator_or_self(student)
return denied unless current_user.type == 'Administrator' || current_user == student
return true
end
def require_administrator
return denied unless current_user && current_user.type == 'Administrator'
return true
end
def require_clubs_permission
return denied unless current_user
return denied unless current_user.clubs_permission?
return true
end
def require_groups_permission
return denied unless current_user
return denied unless current_user.groups_permission?
return true
end
def require_users_permission
return denied unless current_user
return denied unless current_user.users_permission?
return true
end
def require_mailing_lists_permission
return denied unless current_user
return denied unless current_user.mailinglists_permission?
return true
end
def require_site_permission
return denied unless current_user
return denied unless current_user.site_permission?
return true
end
def require_export_permission(club)
return denied unless current_user
return denied unless current_user.export_permission?(club)
return true
end
def require_no_user
if current_user
store_location
redirect_to current_user
return false
end
return true
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def get_default(key)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
val.try(:value)
end
def set_default(key, value)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
if val == nil
val = DefaultValue.new
val.user_id = current_user.id
val.key = key
end
val.value = value
val.save!
end
end
diff --git a/app/views/application/edit_site_settings.html.erb b/app/views/application/edit_site_settings.html.erb
deleted file mode 100644
index 369f7bc..0000000
--- a/app/views/application/edit_site_settings.html.erb
+++ /dev/null
@@ -1,29 +0,0 @@
-<div class="block">
- <div class="secondary-navigation">
- <ul>
- <li class="first active"><%= link_to t(:Edit_Site), edit_site_path %></li>
- <li class="last"><%= link_to t(:Validations), validate_path %></li>
- </ul>
- <div class="clear"></div>
- </div>
- <div class="content">
- <h2 class="title"><%=t(:Edit_Site)%></h2>
- <div class="inner">
- <% form_tag({ :controller => 'application', :action => 'update_site_settings' }, { :class => :form }) do -%>
- <div class="group">
- <%= label_tag 'site_name', t(:Site_Name), :class => 'label' %>
- <%= text_field_tag 'site_name', SiteSettings.site_name, :class => 'text_field' %>
- </div>
-
- <div class="group">
- <%= label_tag 'site_theme', t(:Site_Theme), :class => 'label' %>
- <%= select_tag 'site_theme', options_for_select(@available_themes, SiteSettings.site_theme) %>
- </div>
-
- <div class="group navform">
- <input type="submit" class="button" value="<%=t:Save%> →" />
- </div>
- <% end -%>
- </div>
- </div>
-</div>
diff --git a/app/views/application/edit_site_settings.html.haml b/app/views/application/edit_site_settings.html.haml
new file mode 100644
index 0000000..1d398bd
--- /dev/null
+++ b/app/views/application/edit_site_settings.html.haml
@@ -0,0 +1,22 @@
+.block
+ .secondary-navigation
+ %ul
+ %li.first.active= link_to t(:Edit_Site), edit_site_path
+ %li.last= link_to t(:Validations), validate_path
+ .clear
+ .content
+ %h2.title= t(:Edit_Site)
+ .inner
+ - form_tag({ :controller => 'application', :action => 'update_site_settings' }, { :class => :form }) do
+ .group
+ = label_tag 'site_name', t(:Site_Name), :class => 'label'
+ = text_field_tag 'site_name', SiteSettings.site_name, :class => 'text_field'
+ .group
+ = label_tag 'site_theme', t(:Site_Theme), :class => 'label'
+ = select_tag 'site_theme', options_for_select(@available_themes, SiteSettings.site_theme)
+ .group
+ = label_tag 'welcome_text', t(:Welcome_Text), :class => 'label'
+ = text_area_tag 'welcome_text', SiteSettings.welcome_text, :class => 'text_area', :rows => 10
+ %span.description= t(:Welcome_Text_descr)
+ .group.navform
+ %input.button{ :type => "submit", :value => t(:Save) + " →" }
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 166d356..df57302 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,208 +1,209 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
-
+ Welcome_Text: Welcome Text
+ Welcome_Text_descr: "This is the text that is sent in the welcome email. Use the placeholders %club%, %url% and %password% to denote the current club, URL to log in at and the user's password.."
activerecord:
messages:
in_future: in the future
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index f816a59..e0a8e4d 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,282 +1,284 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
Body_text: Brödtext
Send: Skicka
Subject: Ãrende
From: Från
Back: Tillbaka
Message_sent_to: Meddelandet skickades till
Couldnt_send_to: Kunde inte skicka meddelande till
because_no_email: eftersom de inte har en epostadress.
+ Welcome_Text: Välkomsttext
+ Welcome_Text_descr: "Detta är den text som skickas ut i välkomstbrevet. Använd platshållarna %club%, %url% och %password% för att hänvisa till den aktuella klubben, URL:en att logga in på samt användarens lösenord."
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
in_future: i framtiden
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/test/integration/sitesettings_test.rb b/test/integration/sitesettings_test.rb
new file mode 100644
index 0000000..b139116
--- /dev/null
+++ b/test/integration/sitesettings_test.rb
@@ -0,0 +1,37 @@
+require 'test_helper'
+
+class SiteSettingsTest < ActionController::IntegrationTest
+ def setup
+ create_club_and_admin
+ Factory(:configuration_setting, :setting => :site_name, :value => 'The site')
+ Factory(:configuration_setting, :setting => :welcome_text, :value => 'Welcome text')
+ end
+
+ test "set site name" do
+ log_in_as_admin
+ click_link "Site settings"
+ fill_in "Site name", :with => "New site name"
+ click_button "Save"
+ click_link "Clubs"
+ assert_contain "New site name"
+ assert_not_contain "The site"
+ end
+
+ test "set site theme" do
+ log_in_as_admin
+ click_link "Site settings"
+ select "orange"
+ click_button "Save"
+ click_link "Clubs"
+ #assert_contain "orange/style.css"
+ end
+
+ test "set site welcome" do
+ log_in_as_admin
+ click_link "Site settings"
+ fill_in "Welcome Text", :with => "New welcome text"
+ click_button "Save"
+ click_link "Site settings"
+ assert_contain "New welcome text"
+ end
+end
|
calmh/Register
|
5df28bb70024943c66cda35d38418267641a7978
|
Some trimming and cleaning
|
diff --git a/app/controllers/administrators_controller.rb b/app/controllers/administrators_controller.rb
index 97791c5..2898ced 100644
--- a/app/controllers/administrators_controller.rb
+++ b/app/controllers/administrators_controller.rb
@@ -1,86 +1,83 @@
class AdministratorsController < ApplicationController
before_filter :require_administrator
before_filter :require_users_permission, :only => [ :destroy, :new, :create, :index ]
def index
@admins = Administrator.find(:all)
end
def show
@admin = Administrator.find(params[:id])
@admin = current_user if @admin == nil
end
def new
@admin = Administrator.new
end
def edit
@admin = Administrator.find(params[:id])
end
def create
@admin = Administrator.new(params[:administrator])
- success = @admin.save
- if success
+ if @admin.save
grant_permissions(params[:permission])
flash[:notice] = t:User_created
redirect_to(administrators_path)
else
render :action => "new"
end
end
def update
@admin = Administrator.find(params[:id])
if current_user.users_permission?
- revoke_other_permissions_than(params[:permission])
- grant_permissions(params[:permission])
+ permissions = params[:permission]
+ revoke_other_permissions_than(permissions)
+ grant_permissions(permissions)
end
if @admin.update_attributes(params[:administrator])
flash[:notice] = t(:User_updated)
redirect_to(@admin)
else
render :action => "edit"
end
end
def destroy
@admin = User.find(params[:id])
@admin.destroy
redirect_to(administrators_path)
end
private
def grant_permissions(perms)
return if perms.blank?
perms.each_key do |club_id|
permissions = perms[club_id]
- current_perms = @admin.permissions_for Club.find(club_id)
+ current_perms = @admin.permissions_for(Club.find(club_id))
permissions.each_key do |perm|
if !current_perms.include? perm
- np = Permission.new
- np.club_id = club_id.to_i
- np.user = @admin
- np.permission = perm
- np.save!
+ new_perm = Permission.new(:club_id => club_id, :user => @admin, :permission => perm)
+ new_perm.save!
end
end
end
end
def revoke_other_permissions_than(perms)
if [email protected]?
- @admin.permissions.each do |p|
- c_id = p.club_id.to_s
- if perms.blank? || !perms.key?(c_id) || !perms[c_id].key?(p.permission)
- p.destroy
+ @admin.permissions.each do |permission|
+ c_id = permission.club_id.to_s
+ if perms.blank? || !perms.key?(c_id) || !perms[c_id].key?(permission.permission)
+ permission.destroy
end
end
end
end
end
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index ebf1140..135df2e 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,167 +1,166 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class SiteSettings
def self.get_setting(setting)
- s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
- return "" if s == nil
- return s.value
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
+ return "" if setting == nil
+ return setting.value
end
def self.set_setting(setting, value)
- s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
- if s == nil
- s = ConfigurationSetting.new
- s.setting = setting
+ setting = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
+ if setting == nil
+ setting = ConfigurationSetting.new
+ setting.setting = setting
end
s.value = value
s.save!
end
def self.site_name
get_setting(:site_name)
end
def self.site_name=(value)
set_setting(:site_name, value)
end
def self.site_theme
get_setting(:site_theme)
end
def self.site_theme=(value)
set_setting(:site_theme, value)
end
end
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user
before_filter :set_locale
protect_from_forgery # :secret => '4250e2ff2a2308b6668755ef76677cbb'
before_filter :require_site_permission, :only => [ :edit_site_settings, :update_site_settings ]
def set_locale
session[:locale] = params[:locale] if params[:locale] != nil
I18n.locale = session[:locale] if session[:locale] != nil
end
def edit_site_settings
- @available_themes = Dir.entries("public/stylesheets/themes").select { |d| !d.starts_with? '.' }.sort
+ @available_themes = Dir.entries("public/stylesheets/themes").select { |entry| !entry.starts_with? '.' }.sort
end
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
expire_fragment('layout_header')
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
def validate
require_administrator end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def denied
store_location
flash[:warning] = t(:Must_log_in)
current_user_session.destroy if current_user_session
redirect_to new_user_session_path
return false
end
def require_student_or_administrator
return denied unless current_user
return true
end
def require_administrator_or_self(student)
return denied unless current_user.type == 'Administrator' || current_user == student
return true
end
def require_administrator
return denied unless current_user && current_user.type == 'Administrator'
return true
end
def require_clubs_permission
return denied unless current_user
return denied unless current_user.clubs_permission?
return true
end
def require_groups_permission
return denied unless current_user
return denied unless current_user.groups_permission?
return true
end
def require_users_permission
return denied unless current_user
return denied unless current_user.users_permission?
return true
end
def require_mailing_lists_permission
return denied unless current_user
return denied unless current_user.mailinglists_permission?
return true
end
def require_site_permission
return denied unless current_user
return denied unless current_user.site_permission?
return true
end
def require_export_permission(club)
return denied unless current_user
return denied unless current_user.export_permission?(club)
return true
end
def require_no_user
if current_user
store_location
redirect_to current_user
return false
end
return true
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def get_default(key)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
- return val.value if val != nil
- return nil
+ val.try(:value)
end
def set_default(key, value)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
if val == nil
val = DefaultValue.new
val.user_id = current_user.id
val.key = key
end
val.value = value
val.save!
end
end
diff --git a/app/controllers/clubs_controller.rb b/app/controllers/clubs_controller.rb
index 3bb5027..b6dce91 100644
--- a/app/controllers/clubs_controller.rb
+++ b/app/controllers/clubs_controller.rb
@@ -1,70 +1,49 @@
class ClubsController < ApplicationController
before_filter :require_administrator
before_filter :require_clubs_permission, :only => [ :new, :edit, :create, :destroy, :update ]
def index
@clubs = current_user.clubs.find(:all, :order => 'name')
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @clubs }
- end
end
def show
redirect_to(:controller => 'students', :action => 'index', :club_id => params[:id]) and return
end
def new
@club = Club.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @club }
- end
end
def edit
@club = Club.find(params[:id])
end
def create
@club = Club.new(params[:club])
- respond_to do |format|
- if @club.save
- flash[:notice] = t:Club_created
- format.html { redirect_to(@club) }
- format.xml { render :xml => @club, :status => :created, :location => @club }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @club.errors, :status => :unprocessable_entity }
- end
+ if @club.save
+ flash[:notice] = t:Club_created
+ redirect_to(@club)
+ else
+ render :action => "new"
end
end
def update
@club = Club.find(params[:id])
- respond_to do |format|
- if @club.update_attributes(params[:club])
- flash[:notice] = t:Club_updated
- format.html { redirect_to(@club) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @club.errors, :status => :unprocessable_entity }
- end
+ if @club.update_attributes(params[:club])
+ flash[:notice] = t:Club_updated
+ redirect_to(@club)
+ else
+ render :action => "edit"
end
end
def destroy
@club = Club.find(params[:id])
@club.destroy
- respond_to do |format|
- format.html { redirect_to(clubs_path) }
- format.xml { head :ok }
- end
+ redirect_to(clubs_path)
end
end
diff --git a/app/controllers/graduations_controller.rb b/app/controllers/graduations_controller.rb
index 09a7692..a1186ce 100644
--- a/app/controllers/graduations_controller.rb
+++ b/app/controllers/graduations_controller.rb
@@ -1,110 +1,78 @@
class GraduationsController < ApplicationController
before_filter :require_administrator
- # GET /graduations
- # GET /graduations.xml
def index
@student = Student.find(params[:student_id])
@club = @student.club
@graduations = @student.graduations
- @graduation = Graduation.new
+ @graduation = default_graduation
@graduation.student = @student
- @graduation.grade_id = get_default(:graduation_grade_id)
- @graduation.grade_category_id = get_default(:graduation_grade_category_id)
- @graduation.instructor = get_default(:graduation_instructor)
- @graduation.examiner = get_default(:graduation_examiner)
- @graduation.graduated = DateTime.parse(get_default(:graduation_graduated) || Date.today.to_s)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @graduations }
- end
end
- # GET /graduations/1
- # GET /graduations/1.xml
def show
@graduation = Graduation.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @graduation }
- end
end
def new_bulk
- @graduation = Graduation.new
- @graduation.grade_id = get_default(:graduation_grade_id)
- @graduation.grade_category_id = get_default(:graduation_grade_category_id)
- @graduation.instructor = get_default(:graduation_instructor)
- @graduation.examiner = get_default(:graduation_examiner)
- @graduation.graduated = DateTime.parse(get_default(:graduation_graduated) || DateTime.now.to_s)
+ @graduation = default_graduation
@students = Student.find(session[:selected_students]);
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @graduation }
- end
end
def update_bulk
@students = Student.find(session[:selected_students]);
- @students.each do |s|
- s.graduations << Graduation.new(params[:graduation])
- s.save
+ @students.each do |student|
+ student.graduations << Graduation.new(params[:graduation])
+ student.save
end
session[:selected_students] = nil
@graduation = Graduation.new(params[:graduation])
- set_default(:graduation_grade, @graduation.grade)
- set_default(:graduation_instructor, @graduation.instructor)
- set_default(:graduation_examiner, @graduation.examiner)
- set_default(:graduation_graduated, @graduation.graduated.to_s)
+ update_defaults
redirect_to session[:before_bulk]
end
- # POST /graduations
- # POST /graduations.xml
def create
@graduation = Graduation.new(params[:graduation])
@graduation.save
- set_default(:graduation_grade, @graduation.grade)
- set_default(:graduation_instructor, @graduation.instructor)
- set_default(:graduation_examiner, @graduation.examiner)
- set_default(:graduation_graduated, @graduation.graduated.to_s)
+ update_defaults
+
redirect_to :action => :index
end
- # PUT /graduations/1
- # PUT /graduations/1.xml
def update
@graduation = Graduation.find(params[:id])
- set_default(:graduation_grade, @graduation.grade)
- set_default(:graduation_instructor, @graduation.instructor)
- set_default(:graduation_examiner, @graduation.examiner)
- set_default(:graduation_graduated, @graduation.graduated.to_s)
+ update_defaults
- respond_to do |format|
- if @graduation.update_attributes(params[:graduation])
- format.html { redirect_to(@graduation) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @graduation.errors, :status => :unprocessable_entity }
- end
+ if @graduation.update_attributes(params[:graduation])
+ redirect_to(@graduation)
+ else
+ render :action => "edit"
end
end
- # DELETE /graduations/1
- # DELETE /graduations/1.xml
def destroy
@graduation = Graduation.find(params[:id])
@graduation.destroy
- respond_to do |format|
- format.html { redirect_to(graduations_path) }
- format.xml { head :ok }
- end
+ redirect_to(graduations_path)
+ end
+
+ private
+
+ def update_defaults
+ set_default(:graduation_grade, @graduation.grade)
+ set_default(:graduation_instructor, @graduation.instructor)
+ set_default(:graduation_examiner, @graduation.examiner)
+ set_default(:graduation_graduated, @graduation.graduated.to_s)
+ end
+
+ def default_graduation
+ Graduation.new(:grade_id => get_default(:graduation_grade_id),
+ :grade_category_id => get_default(:graduation_grade_category_id),
+ :instructor => get_default(:graduation_instructor),
+ :examiner => get_default(:graduation_examiner),
+ :graduated => DateTime.parse(get_default(:graduation_graduated) || Date.today.to_s))
end
end
diff --git a/app/controllers/mailing_lists_controller.rb b/app/controllers/mailing_lists_controller.rb
index 8f8e1e9..7ac6f09 100644
--- a/app/controllers/mailing_lists_controller.rb
+++ b/app/controllers/mailing_lists_controller.rb
@@ -1,65 +1,44 @@
class MailingListsController < ApplicationController
before_filter :require_mailing_lists_permission
def index
@mailing_lists = MailingList.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @mailing_lists }
- end
end
def new
@mailing_list = MailingList.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @mailing_list }
- end
end
def edit
@mailing_list = MailingList.find(params[:id])
end
def create
@mailing_list = MailingList.new(params[:mailing_list])
- respond_to do |format|
- if @mailing_list.save
- flash[:notice] = t:Mailing_list_created
- format.html { redirect_to(mailing_lists_path) }
- format.xml { render :xml => @mailing_list, :status => :created, :location => @mailing_list }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @mailing_list.errors, :status => :unprocessable_entity }
- end
+ if @mailing_list.save
+ flash[:notice] = t:Mailing_list_created
+ redirect_to(mailing_lists_path)
+ else
+ render :action => "new"
end
end
def update
@mailing_list = MailingList.find(params[:id])
- respond_to do |format|
- if @mailing_list.update_attributes(params[:mailing_list])
- flash[:notice] = t:Mailing_list_updated
- format.html { redirect_to(mailing_lists_path) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @mailing_list.errors, :status => :unprocessable_entity }
- end
+ if @mailing_list.update_attributes(params[:mailing_list])
+ flash[:notice] = t:Mailing_list_updated
+ redirect_to(mailing_lists_path)
+ else
+ render :action => "edit"
end
end
def destroy
@mailing_list = MailingList.find(params[:id])
@mailing_list.destroy
- respond_to do |format|
- format.html { redirect_to(mailing_lists_path) }
- format.xml { head :ok }
- end
+ redirect_to(mailing_lists_path)
end
end
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
index 79ad642..9594688 100644
--- a/app/controllers/messages_controller.rb
+++ b/app/controllers/messages_controller.rb
@@ -1,30 +1,25 @@
class MessagesController < ApplicationController
def new
- @message = Message.new
- @message.from = current_user.email
- @message.subject = get_default(:message_subject)
- @message.body = get_default(:message_body)
+ @message = Message.new(:from => current_user.email, :subject => get_default(:message_subject), :body => get_default(:message_body))
@students = Student.find(session[:selected_students]);
end
def update
- @message = Message.new
- @message.from = current_user.email
- @message.body = params[:message][:body]
- @message.subject = params[:message][:subject]
- @students = Student.find(session[:selected_students]);
- @sent = []
- @noemail = []
- @students.each do |s|
- if s.email.blank?
+ @message = Message.new(:from => current_user.email, :body => params[:message][:body], :subject => params[:message][:subject])
+ @students = Student.find(session[:selected_students])
+ session[:selected_students] = nil
+
+ @sent = @noemail = []
+ @students.each do |student|
+ if student.email.blank?
@noemail << s
else
- @sent << s if s.deliver_generic_message!(@message)
+ student.deliver_generic_message!(@message)
+ @sent << student
end
end
- session[:selected_students] = nil
set_default(:message_subject, @message.subject)
set_default(:message_body, @message.body)
end
end
diff --git a/app/controllers/payments_controller.rb b/app/controllers/payments_controller.rb
index 42b879d..b545945 100644
--- a/app/controllers/payments_controller.rb
+++ b/app/controllers/payments_controller.rb
@@ -1,57 +1,51 @@
class PaymentsController < ApplicationController
before_filter :require_administrator
def index
@student = Student.find(params[:student_id])
@club = @student.club
@payments = @student.payments
- @payment = Payment.new
- @payment.student_id = @student.id
- @payment.received = DateTime.parse(get_default(:payment_received) || DateTime.now.to_s)
- @payment.amount = get_default(:payment_amount)
- @payment.description = get_default(:payment_description)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @payments }
- end
+ @payment = Payment.new(:student_id => @student.id,
+ :received => DateTime.parse(get_default(:payment_received) || DateTime.now.to_s),
+ :amount => get_default(:payment_amount),
+ :description => get_default(:payment_description))
end
def edit
@payment = Payment.find(params[:id])
end
def create
params[:payment][:amount].sub!(",", ".") # Handle Swedish decimal comma in an ugly way
@payment = Payment.new(params[:payment])
@payment.save!
- set_default(:payment_amount, @payment.amount)
- set_default(:payment_description, @payment.description)
- set_default(:payment_received, @payment.received)
+ update_defaults
+
redirect_to :action => :index
end
def update
@payment = Payment.find(params[:id])
- respond_to do |format|
- if @payment.update_attributes(params[:payment])
- format.html { redirect_to(@payment) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @payment.errors, :status => :unprocessable_entity }
- end
+ if @payment.update_attributes(params[:payment])
+ redirect_to(@payment)
+ else
+ render :action => "edit"
end
end
def destroy
@payment = Payment.find(params[:id])
@payment.destroy
- respond_to do |format|
- format.html { redirect_to(payments_path) }
- format.xml { head :ok }
- end
+ redirect_to(payments_path)
+ end
+
+ private
+
+ def update_defaults
+ set_default(:payment_amount, @payment.amount)
+ set_default(:payment_description, @payment.description)
+ set_default(:payment_received, @payment.received)
end
end
diff --git a/app/controllers/permissions_controller.rb b/app/controllers/permissions_controller.rb
index 3833ecb..bc40173 100644
--- a/app/controllers/permissions_controller.rb
+++ b/app/controllers/permissions_controller.rb
@@ -1,85 +1,46 @@
class PermissionsController < ApplicationController
before_filter :require_administrator
- # GET /permissions
- # GET /permissions.xml
def index
@permissions = Permission.find(:all)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @permissions }
- end
end
- # GET /permissions/1
- # GET /permissions/1.xml
def show
@permission = Permission.find(params[:id])
-
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @permission }
- end
end
- # GET /permissions/new
- # GET /permissions/new.xml
def new
@permission = Permission.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @permission }
- end
end
- # GET /permissions/1/edit
def edit
@permission = Permission.find(params[:id])
end
- # POST /permissions
- # POST /permissions.xml
def create
@permission = Permission.new(params[:permission])
- respond_to do |format|
- if @permission.save
- format.html { redirect_to(@permission) }
- format.xml { render :xml => @permission, :status => :created, :location => @permission }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @permission.errors, :status => :unprocessable_entity }
- end
+ if @permission.save
+ redirect_to(@permission)
+ else
+ render :action => "new"
end
end
- # PUT /permissions/1
- # PUT /permissions/1.xml
def update
@permission = Permission.find(params[:id])
- respond_to do |format|
- if @permission.update_attributes(params[:permission])
- format.html { redirect_to(@permission) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @permission.errors, :status => :unprocessable_entity }
- end
+ if @permission.update_attributes(params[:permission])
+ redirect_to(@permission)
+ else
+ render :action => "edit"
end
end
- # DELETE /permissions/1
- # DELETE /permissions/1.xml
def destroy
@permission = Permission.find(params[:id])
@permission.destroy
- respond_to do |format|
- format.html { redirect_to(permissions_path) }
- format.xml { head :ok }
- end
+ redirect_to(permissions_path)
end
end
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index e88e291..194ac7d 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,311 +1,313 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
set_sort_order(params)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
end
def conditions
variables = []
conditions = []
- if @club_id.respond_to?(:each)
- conditions << "club_id in (?)"
- variables << @club_id
- elsif !@club_id.nil?
- conditions << "club_id = ?"
+ if !@club_id.nil?
+ if @club_id.respond_to?(:each)
+ conditions << "club_id in (?)"
+ else
+ conditions << "club_id = ?"
+ end
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
+ # TODO Redo this with to_proc etc
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
@club = @student.club
set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator'
update_as_admin
else
update_as_self
end
return # Avoid automatic render
end
def update_as_self
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Self_updated)
redirect_to edit_student_path(@student)
else
render :action => "edit"
end
end
def update_as_admin
update_group_membership
update_mailing_list_membership
if @student.update_attributes(params[:student])
flash[:notice] = t(:Student_updated)
redirect_to student_path(@student)
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def respond_to_csv
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
end
end
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to]
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
ml_ids = ml_ids.keys.select do |x|
if cur_ids.include?(x)
true
next
end
ml = MailingList.find(x)
ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
def set_initial_password
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
end
end
|
calmh/Register
|
12c0e991c52bfe79a24cc25df5a3612df8c0d4ba
|
Small clarifications to keep reek happy
|
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index 8bafb84..82c42f6 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -1,61 +1,52 @@
class GroupsController < ApplicationController
before_filter :require_groups_permission
def index
@groups = Group.find(:all, :order => :identifier)
end
def new
@group = Group.new
end
def edit
@group = Group.find(params[:id])
end
def create
@group = Group.new(params[:group])
if @group.save
flash[:notice] = t:Group_created
redirect_to(groups_path)
else
render :action => "new"
end
end
def update
@group = Group.find(params[:id])
- merge_with = Group.find(params[:group][:id])
+ other = Group.find(params[:group][:id])
- if merge_with.id != @group.id
- merge_groups(@group, merge_with)
+ if other.id != @group.id
+ @group.merge_into(other)
redirect_to(groups_path)
else
if @group.update_attributes(params[:group])
flash[:notice] = t:Group_updated
redirect_to(groups_path)
else
render :action => "edit"
end
end
end
def destroy
@group = Group.find(params[:id])
@group.destroy
redirect_to(groups_path)
end
private
-
- def merge_groups(source, destination)
- merge_ids = destination.student_ids
- @group.students.each do |s|
- destination.students << s unless merge_ids.include? s.id
- end
- destination.save!
- source.destroy
- end
end
diff --git a/app/models/administrator.rb b/app/models/administrator.rb
index dbe6837..c9dfaf1 100644
--- a/app/models/administrator.rb
+++ b/app/models/administrator.rb
@@ -1,42 +1,42 @@
class Administrator < User
has_many :permissions, :dependent => :destroy, :foreign_key => 'user_id', :order => "club_id, permission"
has_many :clubs, :through => :permissions, :uniq => true
validates_presence_of :clubs_permission
validates_presence_of :groups_permission
validates_presence_of :users_permission
validates_presence_of :mailinglists_permission
- acts_as_authentic do |c|
- c.validate_login_field = true
- c.validate_email_field = true
- c.validate_password_field = true
- c.require_password_confirmation = true
- c.validates_length_of_login_field_options = { :in => 2..20 }
+ acts_as_authentic do |config|
+ config.validate_login_field = true
+ config.validate_email_field = true
+ config.validate_password_field = true
+ config.require_password_confirmation = true
+ config.validates_length_of_login_field_options = { :in => 2..20 }
end
def permissions_for(club)
permissions.find(:all, :conditions => { :club_id => club.id }).map do
|perm| perm.permission
end
end
def edit_club_permission?(club)
permissions_for(club).include? 'edit'
end
def delete_permission?(club)
permissions_for(club).include? 'delete'
end
def graduations_permission?(club)
permissions_for(club).include? 'graduations'
end
def payments_permission?(club)
permissions_for(club).include? 'payments'
end
def export_permission?(club)
permissions_for(club).include? 'export'
end
end
diff --git a/app/models/club.rb b/app/models/club.rb
index ee3a50b..c811596 100644
--- a/app/models/club.rb
+++ b/app/models/club.rb
@@ -1,11 +1,11 @@
class Club < ActiveRecord::Base
has_many :users, :through => :permissions
has_many :students, :order => "fname, sname", :dependent => :destroy
has_many :permissions, :dependent => :destroy
validates_presence_of :name
validates_uniqueness_of :name
- def <=>(b)
- name <=> b.name
+ def <=>(other)
+ name <=> other.name
end
end
diff --git a/app/models/grade.rb b/app/models/grade.rb
index ffc7263..8f1385d 100644
--- a/app/models/grade.rb
+++ b/app/models/grade.rb
@@ -1,8 +1,8 @@
class Grade < ActiveRecord::Base
validates_presence_of :description, :level
validates_numericality_of :level
- def <=>(b)
- level <=> b.level
+ def <=>(other)
+ level <=> other.level
end
end
diff --git a/app/models/grade_category.rb b/app/models/grade_category.rb
index c7ce5c8..6d0465c 100644
--- a/app/models/grade_category.rb
+++ b/app/models/grade_category.rb
@@ -1,7 +1,7 @@
class GradeCategory < ActiveRecord::Base
validates_presence_of :category
- def <=>(b)
- category <=> b.category
+ def <=>(other)
+ category <=> other.category
end
end
diff --git a/app/models/graduation.rb b/app/models/graduation.rb
index 86fc1e6..822f045 100644
--- a/app/models/graduation.rb
+++ b/app/models/graduation.rb
@@ -1,10 +1,10 @@
class Graduation < ActiveRecord::Base
belongs_to :student
belongs_to :grade
belongs_to :grade_category
validates_presence_of :examiner, :instructor, :graduated, :grade, :grade_category
- def <=>(b)
- grade <=> b.grade
+ def <=>(other)
+ grade <=> other.grade
end
end
diff --git a/app/models/group.rb b/app/models/group.rb
index a35a78d..2d8e75c 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -1,7 +1,16 @@
class Group < ActiveRecord::Base
has_and_belongs_to_many :students, :order => "sname, fname"
def members_in(club)
return students.find(:all, :conditions => { :club_id => club.id })
end
+
+ def merge_into(destination)
+ merge_ids = destination.student_ids
+ self.students.each do |student|
+ destination.students << student unless merge_ids.include?(student.id)
+ end
+ destination.save!
+ destroy
+ end
end
diff --git a/app/models/payment.rb b/app/models/payment.rb
index bddde3b..e192580 100644
--- a/app/models/payment.rb
+++ b/app/models/payment.rb
@@ -1,16 +1,16 @@
class Payment < ActiveRecord::Base
belongs_to :student
validates_numericality_of :amount, :greater_than_or_equal_to => 0.0
validates_presence_of :amount, :description, :received
validate :received_not_in_future
def received_not_in_future
if !received.nil?
errors.add(:recevied, :in_future) unless received <= Time.now
end
end
- def <=>(b)
- received <=> b.received
+ def <=>(other)
+ received <=> other.received
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index 2ee40d6..852e62e 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,146 +1,147 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
validates_uniqueness_of :personal_number, :if => :personal_number_complete?
validate :validate_personal_number,
- :if => lambda { |s| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || s.personal_number_complete? }
- validate :validate_possible_birthdate, :if => lambda { |s| BIRTHDATE_IS_ENOUGH || !s.personal_number.blank? }
+ :if => lambda { |student| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || student.personal_number_complete? }
+ validate :validate_possible_birthdate, :if => lambda { |student| BIRTHDATE_IS_ENOUGH || !student.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
- named_scope :all_inclusive, lambda { |c| {
- :conditions => c, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
+ named_scope :all_inclusive, lambda { |conditions| {
+ :conditions => conditions, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
} }
- acts_as_authentic do |c|
- c.validate_password_field = true
- c.require_password_confirmation = true
- c.validates_length_of_login_field_options = { :in => 2..20 }
+ acts_as_authentic do |config|
+ config.validate_password_field = true
+ config.require_password_confirmation = true
+ config.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
- personal_number.sub("-", "").split(//)[2..-1].each do |n|
- (n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
+ self.personal_number.sub("-", "").split(//)[2..-1].each do |digit|
+ (digit.to_i * fact).to_s.split(//).each do |fact_digit|
+ sum += fact_digit.to_i
+ end
fact = 3 - fact
end
sum % 10
end
def personal_number_valid_format?
personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
end
def personal_number_complete?
!personal_number.blank? && personal_number_valid_format?
end
def validate_personal_number
if personal_number_valid_format?
if luhn != 0
errors.add(:personal_number, :incorrect_check_digit)
end
else
errors.add(:personal_number, :invalid)
end
end
def validate_possible_birthdate
return if personal_number.blank?
return if personal_number_valid_format?
if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
- value = $1 + "-" + $2 if value =~ /^(\d\d\d\d\d\d)(\d\d\d\d)$/;
- value = $1 + "-" + $2 if value =~ /^(19\d\d\d\d\d\d)(\d\d\d\d)$/;
- value = $1 + "-" + $2 if value =~ /^(20\d\d\d\d\d\d)(\d\d\d\d)$/;
+ value = $1 + $2 + "-" + $3 if value =~ /^(19|20|)(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
- p = Payment.new
- p.amount = 0
- p.received = created_at
- p.description = "Start"
- return p
+ payment = Payment.new
+ payment.amount = 0
+ payment.received = created_at
+ payment.description = "Start"
+ return payment
end
end
def current_grade
- if graduations.blank?
+ my_graduations = self.graduations
+ if my_graduations.blank?
return nil
else
- in_main_interest = graduations.select { |g| g.grade_category == main_interest }
+ in_main_interest = my_graduations.select { |graduation| graduation.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
- return graduations[0]
+ return my_graduations[0]
end
end
end
def active?
+ reference = Time.now
if payments.blank?
- return Time.now - created_at < 86400 * 45
+ return reference - created_at < 86400 * 45
else
- return Time.now - payments[0].received < 86400 * 180
+ return reference - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
- return self[:gender] unless self[:gender].blank?
- return 'unknown'
+ return self[:gender] || 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
- d = Date.new($1.to_i, $2.to_i, $3.to_i)
- return ((Date.today-d) / 365.24).to_i
+ date_of_birth = Date.new($1.to_i, $2.to_i, $3.to_i)
+ return ((Date.today - date_of_birth) / 365.24).to_i
else
return -1
end
end
def group_list
- groups.map{ |g| g.identifier }.join(", ")
+ groups.map{ |group| group.identifier }.join(", ")
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 7049b68..7f599fb 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,24 +1,24 @@
class User < ActiveRecord::Base
- acts_as_authentic do |c|
+ acts_as_authentic do |config|
Authlogic::CryptoProviders::Sha1.stretches = 1
- c.transition_from_crypto_providers = Authlogic::CryptoProviders::Sha1
- c.crypto_provider = Authlogic::CryptoProviders::Sha256
- c.validate_login_field = false
- c.validate_email_field = false
- c.validate_password_field = false
- c.require_password_confirmation = false
+ config.transition_from_crypto_providers = Authlogic::CryptoProviders::Sha1
+ config.crypto_provider = Authlogic::CryptoProviders::Sha256
+ config.validate_login_field = false
+ config.validate_email_field = false
+ config.validate_password_field = false
+ config.require_password_confirmation = false
end
def self.find_by_login_or_email(login)
User.find_by_login(login) || User.find_by_email(login)
end
def deliver_password_reset_instructions!
reset_perishable_token!
Notifier.deliver_password_reset_instructions(self)
end
def deliver_generic_message!(message)
Notifier.deliver_generic_message(self, message)
end
end
|
calmh/Register
|
b9555a99ce3a3b767d9adc2577b761b293bf9893
|
Slight cleanups
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 61d0547..ebf1140 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,171 +1,167 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class SiteSettings
def self.get_setting(setting)
s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
return "" if s == nil
return s.value
end
def self.set_setting(setting, value)
s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
if s == nil
s = ConfigurationSetting.new
s.setting = setting
end
s.value = value
s.save!
end
def self.site_name
get_setting(:site_name)
end
def self.site_name=(value)
set_setting(:site_name, value)
end
def self.site_theme
get_setting(:site_theme)
end
def self.site_theme=(value)
set_setting(:site_theme, value)
end
end
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user
before_filter :set_locale
protect_from_forgery # :secret => '4250e2ff2a2308b6668755ef76677cbb'
before_filter :require_site_permission, :only => [ :edit_site_settings, :update_site_settings ]
def set_locale
session[:locale] = params[:locale] if params[:locale] != nil
I18n.locale = session[:locale] if session[:locale] != nil
end
def edit_site_settings
- begin
- @available_themes = Dir.entries("public/stylesheets/themes").select { |d| !d.starts_with? '.' }.sort
- rescue Exception => e
- @available_themes = []
- end
+ @available_themes = Dir.entries("public/stylesheets/themes").select { |d| !d.starts_with? '.' }.sort
end
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
expire_fragment('layout_header')
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
def validate
require_administrator end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def denied
store_location
flash[:warning] = t(:Must_log_in)
current_user_session.destroy if current_user_session
redirect_to new_user_session_path
return false
end
def require_student_or_administrator
return denied unless current_user
return true
end
def require_administrator_or_self(student)
return denied unless current_user.type == 'Administrator' || current_user == student
return true
end
def require_administrator
return denied unless current_user && current_user.type == 'Administrator'
return true
end
def require_clubs_permission
return denied unless current_user
return denied unless current_user.clubs_permission?
return true
end
def require_groups_permission
return denied unless current_user
return denied unless current_user.groups_permission?
return true
end
def require_users_permission
return denied unless current_user
return denied unless current_user.users_permission?
return true
end
def require_mailing_lists_permission
return denied unless current_user
return denied unless current_user.mailinglists_permission?
return true
end
def require_site_permission
return denied unless current_user
return denied unless current_user.site_permission?
return true
end
def require_export_permission(club)
return denied unless current_user
return denied unless current_user.export_permission?(club)
return true
end
def require_no_user
if current_user
store_location
redirect_to current_user
return false
end
return true
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def get_default(key)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
return val.value if val != nil
return nil
end
def set_default(key, value)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
if val == nil
val = DefaultValue.new
val.user_id = current_user.id
val.key = key
end
val.value = value
val.save!
end
end
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 42db200..e88e291 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,293 +1,311 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
+ set_sort_order(params)
+
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
+ @group_id = int_or_nil(params[:gi])
+ @grade = int_or_nil(params[:gr])
+ @title_id = int_or_nil(params[:ti])
+ @board_position_id = int_or_nil(params[:bp])
+ @club_position_id = int_or_nil(params[:cp])
+ @only_active = (params[:a].to_i == 1)
+ end
+
+ def set_sort_order(params)
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
-
- @group_id = int_or_nil(params[:gi])
- @grade = int_or_nil(params[:gr])
- @title_id = int_or_nil(params[:ti])
- @board_position_id = int_or_nil(params[:bp])
- @club_position_id = int_or_nil(params[:cp])
- @only_active = (params[:a].to_i == 1)
end
def conditions
variables = []
conditions = []
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
variables << @club_id
elsif !@club_id.nil?
conditions << "club_id = ?"
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
- format.csv do
- if @club.nil? || require_export_permission(@club)
- send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
- return
- end
- end
+ format.csv { respond_to_csv }
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
-
- # This is an ugly hack that uses the random perishable token as a base password for the user.
- @student.reset_perishable_token!
- @student.password = @student.password_confirmation = @student.perishable_token
- @student.reset_perishable_token!
-
@club = @student.club
+ set_initial_password
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
- update_group_membership if current_user.kind_of? Administrator
- update_mailing_list_membership
+ if current_user.type == 'Administrator'
+ update_as_admin
+ else
+ update_as_self
+ end
+ return # Avoid automatic render
+ end
- success = @student.update_attributes(params[:student])
+ def update_as_self
+ update_mailing_list_membership
- if current_user.type == 'Administrator'
- flash[:notice] = t(:Student_updated) if success
- redirect = student_path(@student)
- elsif current_user.type == 'Student'
- flash[:notice] = t(:Self_updated) if success
- redirect = edit_student_path(@student)
+ if @student.update_attributes(params[:student])
+ flash[:notice] = t(:Self_updated)
+ redirect_to edit_student_path(@student)
+ else
+ render :action => "edit"
end
+ end
- if success
- redirect_to redirect
+ def update_as_admin
+ update_group_membership
+ update_mailing_list_membership
+
+ if @student.update_attributes(params[:student])
+ flash[:notice] = t(:Student_updated)
+ redirect_to student_path(@student)
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
+ def respond_to_csv
+ if @club.nil? || require_export_permission(@club)
+ send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
+ end
+ end
+
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
def update_group_membership
if !params.key?(:member_of)
@student.groups.clear
else
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
end
def update_mailing_list_membership
if !params.key? :subscribes_to
# You always have the right to unsubscribe from mailing lists
@student.mailing_lists.clear
else
ml_ids = params[:subscribes_to]
if !current_user.kind_of? Administrator
cur_ids = @student.mailing_list_ids
ml_ids = ml_ids.keys.select do |x|
- if cur_ids.include?(x)
- true
- next
- end
- ml = MailingList.find(x)
- ml.security == 'public' && ( ml.club == nil || ml.club == @club )
+ if cur_ids.include?(x)
+ true
+ next
+ end
+ ml = MailingList.find(x)
+ ml.security == 'public' && ( ml.club == nil || ml.club == @club )
end
end
@student.mailing_list_ids = ml_ids
end
end
+
+ def set_initial_password
+ # This is an ugly hack that uses the random perishable token as a base password for the user.
+ @student.reset_perishable_token!
+ @student.password = @student.password_confirmation = @student.perishable_token
+ @student.reset_perishable_token!
+ end
end
|
calmh/Register
|
41dd30945f29428c65fdb79bfc25862f764802d8
|
Cleanup, simplification and more tests
|
diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb
index aff85fd..8bafb84 100644
--- a/app/controllers/groups_controller.rb
+++ b/app/controllers/groups_controller.rb
@@ -1,87 +1,61 @@
class GroupsController < ApplicationController
before_filter :require_groups_permission
- # GET /groups
- # GET /groups.xml
def index
@groups = Group.find(:all, :order => :identifier)
-
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @groups }
- end
end
- # GET /groups/new
- # GET /groups/new.xml
def new
@group = Group.new
-
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @group }
- end
end
- # GET /groups/1/edit
def edit
@group = Group.find(params[:id])
end
- # POST /groups
- # POST /groups.xml
def create
@group = Group.new(params[:group])
- respond_to do |format|
- if @group.save
- flash[:notice] = t:Group_created
- format.html { redirect_to(groups_path) }
- format.xml { render :xml => @group, :status => :created, :location => @group }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
- end
+ if @group.save
+ flash[:notice] = t:Group_created
+ redirect_to(groups_path)
+ else
+ render :action => "new"
end
end
- # PUT /groups/1
- # PUT /groups/1.xml
def update
@group = Group.find(params[:id])
merge_with = Group.find(params[:group][:id])
- merge_ids = merge_with.student_ids
if merge_with.id != @group.id
- @group.students.each do |s|
- merge_with.students<<s unless merge_ids.include? s.id
- end
- merge_with.save!
- @group.destroy
+ merge_groups(@group, merge_with)
redirect_to(groups_path)
else
- respond_to do |format|
- if @group.update_attributes(params[:group])
- flash[:notice] = t:Group_updated
- format.html { redirect_to(groups_path) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @group.errors, :status => :unprocessable_entity }
- end
+ if @group.update_attributes(params[:group])
+ flash[:notice] = t:Group_updated
+ redirect_to(groups_path)
+ else
+ render :action => "edit"
end
end
end
- # DELETE /groups/1
- # DELETE /groups/1.xml
def destroy
@group = Group.find(params[:id])
@group.destroy
- respond_to do |format|
- format.html { redirect_to(groups_path) }
- format.xml { head :ok }
+ redirect_to(groups_path)
+ end
+
+ private
+
+ def merge_groups(source, destination)
+ merge_ids = destination.student_ids
+ @group.students.each do |s|
+ destination.students << s unless merge_ids.include? s.id
end
+ destination.save!
+ source.destroy
end
end
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 3cbd4ae..42db200 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,274 +1,293 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize(params = nil)
if params.key? :ci
@club_id = params[:ci].map{ |x| x.to_i }
else
@club_id = Club.all.map { |c| c.id }
end
if !params[:c].blank?
@sort_field = params[:c]
else
@sort_field = params[:c] = 'name'
end
if !params[:d].blank?
@sort_order = params[:d]
else
@sort_order = params[:d] = 'up'
end
@group_id = int_or_nil(params[:gi])
@grade = int_or_nil(params[:gr])
@title_id = int_or_nil(params[:ti])
@board_position_id = int_or_nil(params[:bp])
@club_position_id = int_or_nil(params[:cp])
@only_active = (params[:a].to_i == 1)
end
def conditions
variables = []
conditions = []
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
variables << @club_id
elsif !@club_id.nil?
conditions << "club_id = ?"
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort { |a, b| compare(a, b) }
end
end
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
@group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
private
def int_or_nil(val)
return nil if val.blank?
return val.to_i
end
def compare(a, b)
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv do
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
return
end
end
end
end
def load_searchparams
@searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
- if current_user.type == 'Administrator' && params.key?(:member_of)
- group_ids = params[:member_of].keys
- @student.group_ids = group_ids
- else
- @student.groups.clear
- end
-
- # TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
- if params.key? :subscribes_to
- ml_ids = params[:subscribes_to].keys
- @student.mailing_list_ids = ml_ids
- else
- @student.mailing_lists.clear
- end
+ update_group_membership if current_user.kind_of? Administrator
+ update_mailing_list_membership
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
+
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
+
+ def update_group_membership
+ if !params.key?(:member_of)
+ @student.groups.clear
+ else
+ group_ids = params[:member_of].keys
+ @student.group_ids = group_ids
+ end
+ end
+
+ def update_mailing_list_membership
+ if !params.key? :subscribes_to
+ # You always have the right to unsubscribe from mailing lists
+ @student.mailing_lists.clear
+ else
+ ml_ids = params[:subscribes_to]
+ if !current_user.kind_of? Administrator
+ cur_ids = @student.mailing_list_ids
+ ml_ids = ml_ids.keys.select do |x|
+ if cur_ids.include?(x)
+ true
+ next
+ end
+ ml = MailingList.find(x)
+ ml.security == 'public' && ( ml.club == nil || ml.club == @club )
+ end
+ end
+ @student.mailing_list_ids = ml_ids
+ end
+ end
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index c8676a1..ccecf95 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,157 +1,210 @@
require 'test_helper'
class StudentsTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@category = Factory(:grade_category)
@students = 10.times.map { Factory(:student, :club => @club) }
end
- test "student page should show all students" do
- log_in_as_admin
- click_link "Clubs"
- click_link @club.name
- @students.each do |s|
- assert_contain s.name
- end
- assert_contain " #{@students.length} students"
- end
-
- test "should not create new blank student" do
- log_in_as_admin
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- click_button "Save"
-
- assert_not_contain "created"
- assert_contain "can't be blank"
- end
-
- test "should create new student with minimal info" do
- log_in_as_admin
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- fill_in "Name", :with => "Test"
- fill_in "Surname", :with => "Testsson"
- fill_in "Personal number", :with => "19850203"
- select @category.category
- click_button "Save"
-
- assert_contain "created"
- end
-
- test "should create a new student in x groups" do
- @admin.groups_permission = true
- @admin.save
+ test "student page should show all students" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ @students.each do |s|
+ assert_contain s.name
+ end
+ assert_contain " #{@students.length} students"
+ end
+
+ test "should not create new blank student" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ click_button "Save"
+
+ assert_not_contain "created"
+ assert_contain "can't be blank"
+ end
+
+ test "should create new student with minimal info" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ select @category.category
+ click_button "Save"
+
+ assert_contain "created"
+ end
+
+ test "should create a new student in x groups" do
+ @admin.groups_permission = true
+ @admin.save
all_groups = 4.times.map { Factory(:group) }
member_groups = all_groups[1..2]
non_member_groups = all_groups - member_groups
log_in_as_admin
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- fill_in "Name", :with => "Test"
- fill_in "Surname", :with => "Testsson"
- fill_in "Personal number", :with => "19850203"
- member_groups.each do |g|
- check g.identifier
- end
- click_button "Save"
- assert_contain "created"
-
- member_groups.each do |g|
- click_link "Groups"
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ member_groups.each do |g|
+ check g.identifier
+ end
+ click_button "Save"
+ assert_contain "created"
+
+ member_groups.each do |g|
+ click_link "Groups"
click_link g.identifier
- assert_contain "Test Testsson"
+ assert_contain "Test Testsson"
end
- non_member_groups.each do |g|
- click_link "Groups"
+ non_member_groups.each do |g|
+ click_link "Groups"
click_link g.identifier
- assert_not_contain "Test Testsson"
+ assert_not_contain "Test Testsson"
end
- end
+ end
- test "should create a new student in x mailing lists" do
- @admin.mailinglists_permission = true
- @admin.save
+ test "should create a new student in x mailing lists" do
+ @admin.mailinglists_permission = true
+ @admin.save
all_lists = 4.times.map { Factory(:mailing_list) }
member_lists = all_lists[1..2]
non_member_lists = all_lists - member_lists
log_in_as_admin
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- fill_in "Name", :with => "Test"
- fill_in "Surname", :with => "Testsson"
- fill_in "Personal number", :with => "19850203"
- member_lists.each do |m|
- check m.description
- end
- click_button "Save"
- assert_contain "created"
-
- member_lists.each do |m|
- click_link "Mailing Lists"
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ member_lists.each do |m|
+ check m.description
+ end
+ click_button "Save"
+ assert_contain "created"
+
+ member_lists.each do |m|
+ click_link "Mailing Lists"
click_link m.email
- assert_contain "Test Testsson"
+ assert_contain "Test Testsson"
end
- non_member_lists.each do |m|
- click_link "Mailing Lists"
+ non_member_lists.each do |m|
+ click_link "Mailing Lists"
click_link m.email
- assert_not_contain "Test Testsson"
+ assert_not_contain "Test Testsson"
end
- end
-
- test "new student should join club mailing list per default" do
- mailing_list = Factory(:mailing_list, :default => 1)
- @admin.mailinglists_permission = true
- @admin.save
- log_in_as_admin
-
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- fill_in "Name", :with => "Test"
- fill_in "Surname", :with => "Testsson"
- fill_in "Personal number", :with => "19850203"
- click_button "Save"
-
- click_link "Mailing Lists"
- click_link mailing_list.email
-
- assert_contain "Test Testsson"
- end
-
- test "new student should not join other club mailing list per default" do
- other_club = Factory(:club)
- mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
- @admin.mailinglists_permission = true
- @admin.save
- log_in_as_admin
-
- click_link "Clubs"
- click_link @club.name
- click_link "New student"
-
- fill_in "Name", :with => "Test"
- fill_in "Surname", :with => "Testsson"
- fill_in "Personal number", :with => "19850203"
- click_button "Save"
-
- click_link "Mailing Lists"
- click_link mailing_list.email
-
- assert_not_contain "Test Testsson"
- end
+ end
+
+ test "new student should join club mailing list per default" do
+ mailing_list = Factory(:mailing_list, :default => 1)
+ @admin.mailinglists_permission = true
+ @admin.save
+ log_in_as_admin
+
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ click_button "Save"
+
+ click_link "Mailing Lists"
+ click_link mailing_list.email
+
+ assert_contain "Test Testsson"
+ end
+
+ test "new student should not join other club mailing list per default" do
+ other_club = Factory(:club)
+ mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
+ @admin.mailinglists_permission = true
+ @admin.save
+ log_in_as_admin
+
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ click_button "Save"
+
+ click_link "Mailing Lists"
+ click_link mailing_list.email
+
+ assert_not_contain "Test Testsson"
+ end
+
+ test "student should be able to edit self without losing groups" do
+ student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
+ group = Factory(:group)
+ student.groups << group;
+ student.save!
+
+ visit "/?locale=en"
+ fill_in "Login", :with => student.email
+ fill_in "Password", :with => "password"
+ click_button "Log in"
+
+ click_button "Save"
+
+ student_from_db = Student.find(student.id)
+ assert student_from_db.groups.length == 1
+ end
+
+ test "student should join mailing list" do
+ student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
+ mailing_list = Factory(:mailing_list)
+
+ visit "/?locale=en"
+ fill_in "Login", :with => student.email
+ fill_in "Password", :with => "password"
+ click_button "Log in"
+
+ check mailing_list.description
+ click_button "Save"
+
+ student_from_db = Student.find(student.id)
+ assert student_from_db.mailing_list_ids == [ mailing_list.id ]
+ end
+
+ test "student should join one mailing list and leave another" do
+ student = Factory(:student, :club => @club, :email => "[email protected]", :password => "password", :password_confirmation => "password")
+ mailing_lists = 2.times.map { Factory(:mailing_list) }
+ student.mailing_lists << mailing_lists[1]
+ student.save!
+
+ visit "/?locale=en"
+ fill_in "Login", :with => student.email
+ fill_in "Password", :with => "password"
+ click_button "Log in"
+
+ check mailing_lists[0].description
+ uncheck mailing_lists[1].description
+ click_button "Save"
+
+ student_from_db = Student.find(student.id)
+ assert student_from_db.mailing_list_ids.include?(mailing_lists[0].id)
+ assert !student_from_db.mailing_list_ids.include?(mailing_lists[1].id)
+ end
end
|
calmh/Register
|
c513de86fe5f00b72812be251a8eb0a3dc4e29ee
|
Student for log in tests
|
diff --git a/db/seeds.rb b/db/seeds.rb
index c397878..0def704 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,28 +1,29 @@
Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
admin = Factory(:administrator, :login => 'admin',
:password => 'admin', :password_confirmation => 'admin',
:groups_permission => true,
:mailinglists_permission => true,
:clubs_permission => true,
:users_permission => true,
:site_permission => true
)
club = Factory(:club)
10.times do
Factory(:student, :club => club)
end
+Factory(:student, :club => club, :email => "[email protected]", :password => "student", :password_confirmation => "student")
%w[read edit delete graduations payments export].each do |perm|
Factory(:permission, :club => club, :user => admin, :permission => perm)
end
4.times do
Factory(:mailing_list)
end
4.times do
Factory(:group)
end
|
calmh/Register
|
26c11c8bf78c090b50eb2ab528235725f97bb326
|
Haml conversion
|
diff --git a/app/views/students/_self_form.html.erb b/app/views/students/_self_form.html.erb
deleted file mode 100644
index 6288121..0000000
--- a/app/views/students/_self_form.html.erb
+++ /dev/null
@@ -1,52 +0,0 @@
-<div class="group">
- <%= f.label :main_interest_id, t(:Main_Interest), :class => :label %>
- <%= select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] } %><br/>
-</div>
-
-<div class="group">
- <%= f.label :email, t(:Email), :class => :label %>
- <%= f.text_field :email, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :mailing_lists, t(:Mailing_Lists), :class => :label %>
- <% mailing_lists.each do |ml| -%>
- <% if ml.security == 'public' && ( ml.club == nil || ml.club == @club ) -%>
- <label><td><%= check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id) %> <%=ml.description%></label><br/>
- <% else -%>
- <%= hidden_field_tag "subscribes_to[" + ml.id.to_s + "]", value = @student.mailing_list_ids.include?(ml.id) ? "1" : "0" %>
- <% end -%>
- <% end -%>
-</table>
-</div>
-
-<div class="group">
- <%= f.label :home_phone, t(:Home_phone), :class => :label %>
- <%= f.text_field :home_phone, :class => 'text_field' %>
- <span class="description"><%=t :Phone_number_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :mobile_phone, t(:Mobile_phone), :class => :label %>
- <%= f.text_field :mobile_phone, :class => 'text_field' %>
- <span class="description"><%=t :Phone_number_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :street, t(:Street), :class => :label %>
- <%= f.text_field :street, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :zipcode, t(:Zipcode), :class => :label %>
- <%= f.text_field :zipcode, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :city, t(:City), :class => :label %>
- <%= f.text_field :city, :class => 'text_field' %>
-</div>
-
-<div class="group navform">
- <input type="submit" class="button" value="<%=t :Save%> →" />
-</div>
diff --git a/app/views/students/_self_form.html.haml b/app/views/students/_self_form.html.haml
new file mode 100644
index 0000000..bf87855
--- /dev/null
+++ b/app/views/students/_self_form.html.haml
@@ -0,0 +1,43 @@
+.group
+ = f.label :main_interest_id, t(:Main_Interest), :class => :label
+ = select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] }
+ %br
+
+.group
+ = f.label :email, t(:Email), :class => :label
+ = f.text_field :email, :class => 'text_field'
+
+.group
+ %label.label= t(:Mailing_Lists)
+ - mailing_lists.each do |ml|
+ - if ml.security == 'public' && ( ml.club == nil || ml.club == @club )
+ = check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id)
+ %label{ :for => "subscribes_to_" + ml.id.to_s }= ml.description
+ %br
+ - else
+ = hidden_field_tag "subscribes_to[" + ml.id.to_s + "]", value = @student.mailing_list_ids.include?(ml.id) ? "1" : "0"
+
+.group
+ = f.label :home_phone, t(:Home_phone), :class => :label
+ = f.text_field :home_phone, :class => 'text_field'
+ %span.description= t(:Phone_number_descr)
+
+.group
+ = f.label :mobile_phone, t(:Mobile_phone), :class => :label
+ = f.text_field :mobile_phone, :class => 'text_field'
+ %span.description= t(:Phone_number_descr)
+
+.group
+ = f.label :street, t(:Street), :class => :label
+ = f.text_field :street, :class => 'text_field'
+
+.group
+ = f.label :zipcode, t(:Zipcode), :class => :label
+ = f.text_field :zipcode, :class => 'text_field'
+
+.group
+ = f.label :city, t(:City), :class => :label
+ = f.text_field :city, :class => 'text_field'
+
+.group.navform
+ %input.button{ :type => "submit", :value => t(:Save) + " →" }
|
calmh/Register
|
06cae219efbbaf1d36b3e9be9d71961b0eb17404
|
Simplify SearchParams and write up some tests for sorting.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 7db2e0c..3cbd4ae 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,254 +1,274 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
- def initialize
- @club_id = Club.all.map { |c| c.id }
- @sort_field = 'fname'
- @sort_order = 'up'
+ def initialize(params = nil)
+ if params.key? :ci
+ @club_id = params[:ci].map{ |x| x.to_i }
+ else
+ @club_id = Club.all.map { |c| c.id }
+ end
+
+ if !params[:c].blank?
+ @sort_field = params[:c]
+ else
+ @sort_field = params[:c] = 'name'
+ end
+
+ if !params[:d].blank?
+ @sort_order = params[:d]
+ else
+ @sort_order = params[:d] = 'up'
+ end
+
+ @group_id = int_or_nil(params[:gi])
+ @grade = int_or_nil(params[:gr])
+ @title_id = int_or_nil(params[:ti])
+ @board_position_id = int_or_nil(params[:bp])
+ @club_position_id = int_or_nil(params[:cp])
+ @only_active = (params[:a].to_i == 1)
end
def conditions
variables = []
conditions = []
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
variables << @club_id
elsif !@club_id.nil?
conditions << "club_id = ?"
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
- return students.sort do |a, b|
- af = a.send(@sort_field)
- bf = b.send(@sort_field)
- if !af.nil? && !bf.nil?
- r = af <=> bf
- elsif af.nil? && !bf.nil?
- r = -1
- elsif !af.nil? && bf.nil?
- r = 1
- else
- r = 0
- end
- r = -r if @sort_order == 'down'
- r
- end
+ return students.sort { |a, b| compare(a, b) }
end
end
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
+ @group_id = @group_id.to_i
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
+
+ private
+
+ def int_or_nil(val)
+ return nil if val.blank?
+ return val.to_i
+ end
+
+ def compare(a, b)
+ af = a.send(@sort_field)
+ bf = b.send(@sort_field)
+ if !af.nil? && !bf.nil?
+ r = af <=> bf
+ elsif af.nil? && !bf.nil?
+ r = -1
+ elsif !af.nil? && bf.nil?
+ r = 1
+ else
+ r = 0
+ end
+ r = -r if @sort_order == 'down'
+ r
+ end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv do
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
return
end
end
end
end
def load_searchparams
- @searchparams = SearchParams.new
- @searchparams.group_id = params[:gi].to_i unless params[:gi].blank?
- @searchparams.grade = params[:gr].to_i unless params[:gr].blank?
- @searchparams.title_id = params[:ti].to_i unless params[:ti].blank?
- @searchparams.board_position_id = params[:bp].to_i unless params[:bp].blank?
- @searchparams.club_position_id = params[:cp].to_i unless params[:cp].blank?
- @searchparams.only_active = params[:a].to_i unless params[:a].blank?
- @searchparams.sort_field = params[:c] unless params[:c].blank?
- @searchparams.sort_order = params[:d] unless params[:d].blank?
- if params.key? :ci
- @searchparams.club_id = params[:ci].map{|x| x.to_i}
- end
+ @searchparams = SearchParams.new(params)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_message"
redirect_to :controller => 'messages', :action => 'new'
end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/views/students/_list.html.haml b/app/views/students/_list.html.haml
index b81c7dc..1fa3cb7 100644
--- a/app/views/students/_list.html.haml
+++ b/app/views/students/_list.html.haml
@@ -1,32 +1,32 @@
- form_tag :controller => 'students', :action => 'bulk_operations', :class => "form", :method => "post" do
%table.table.lesspadding
%tr
%th.first
- %th= sort_link t(:Name), :fname
+ %th= sort_link t(:Name), :name
- if @displayClubField
%th= sort_link t(:Club), :club
%th= sort_link t(:Main_Interest), :main_interest
%th= t(:Groups)
%th= sort_link t(:Personal_Num), :personal_number
- if @displayPaymentField
%th= sort_link t(:Grade), :current_grade
%th.last= sort_link t(:Latest_Payment), :latest_payment
- else
%th.last= sort_link t(:Grade), :current_grade
- @students.each do |student|
%tr{ :class => cycle("odd", "even") }
%td= check_box_tag "selected_students[]", student.id, false, { :id => 'selected_students_' + student.id.to_s }
%td= link_to student.name, student_path(student)
- if @displayClubField
%td= link_to student.club.name, club_path(student.club)
%td= student.main_interest.category
%td= student.groups.map{ |g| g.identifier }.join(", ")
%td= student.personal_number
%td= grade_str(student.current_grade)
- if @displayPaymentField
%td{ :class => "student-" + (student.active? ? 'active' : 'inactive')}=h student.latest_payment.description
.group.navform
%p= t(:Acts_on_selected)
- if current_user.clubs_permission? || current_user.graduations_permission?(@club)
= submit_tag t(:Register_Graduation) + " →", :name => "bulk_graduations", :class => "button", :id => "bulk_graduations"
= submit_tag t(:Send_Message) + " →", :name => "bulk_message", :class => "button", :id => "bulk_message"
diff --git a/test/integration/viewing_test.rb b/test/integration/viewing_test.rb
index 1bf9aaa..4a3a4f7 100644
--- a/test/integration/viewing_test.rb
+++ b/test/integration/viewing_test.rb
@@ -1,72 +1,119 @@
require 'test_helper'
class ViewingTest < ActionController::IntegrationTest
def setup
create_club_and_admin
@admin.clubs_permission = true
@admin.save
@students = [
Factory(:student, :fname => "Aa", :sname => "Bb", :club => @club),
Factory(:student, :fname => "Bb", :sname => "Cc", :club => @club),
Factory(:student, :fname => "Cc", :sname => "Dd", :club => @club),
Factory(:student, :fname => "Dd", :sname => "Ee", :club => @club)
]
@students.each do |s|
Factory(:payment, :student => s, :received => 14.months.ago)
end
@active_students = @students[1..2]
@active_students.each do |s|
Factory(:payment, :student => s, :received => 2.months.ago)
end
@inactive_students = @students - @active_students
+
+ @group = Factory(:group)
+ @grade = Factory(:grade)
+ @inactive_students.each do |s|
+ s.groups << @group
+ Factory(:graduation, :grade => @grade, :student => s)
+ s.save
+ end
end
- test "verify student sorting" do
+ test "verify student sorting defaults" do
log_in_as_admin
click_link "Clubs"
click_link @club.name
assert_contain /Aa Bb.*Bb Cc.*Cc Dd.*Dd Ee/m
click_link "Search Students"
assert_contain /Aa Bb.*Bb Cc.*Cc Dd.*Dd Ee/m
end
+ test "verify student sorting reverse name" do
+ log_in_as_admin
+
+ click_link "Clubs"
+ click_link @club.name
+ click_link "Name"
+ assert_contain /Dd Ee.*Cc Dd.*Bb Cc.*Aa Bb/m
+ end
+
test "verify only active filtering" do
log_in_as_admin
- click_link "clubs"
+ click_link "Clubs"
click_link @club.name
@students.each do |s|
assert_contain s.name
end
check "a"
click_button "Search"
@active_students.each do |s|
assert_contain s.name
end
@inactive_students.each do |s|
assert_not_contain s.name
end
click_button "Search"
@active_students.each do |s|
assert_contain s.name
end
@inactive_students.each do |s|
assert_not_contain s.name
end
uncheck "a"
click_button "Search"
@students.each do |s|
assert_contain s.name
end
end
+
+ test "should only display students in group" do
+ log_in_as_admin
+
+ click_link "Search Students"
+ select @group.identifier
+ click_button "Search"
+
+ @inactive_students.each do |s|
+ assert_contain s.name
+ end
+ @active_students.each do |s|
+ assert_not_contain s.name
+ end
+ end
+
+ test "should only display students with grade" do
+ log_in_as_admin
+
+ click_link "Search Students"
+ select @grade.description
+ click_button "Search"
+
+ @inactive_students.each do |s|
+ assert_contain s.name
+ end
+ @active_students.each do |s|
+ assert_not_contain s.name
+ end
+ end
end
|
calmh/Register
|
ce739c8b4a4c2435b2fc9c0c8b24957b559085c7
|
Simplify administrators controller and write up some tests
|
diff --git a/app/controllers/administrators_controller.rb b/app/controllers/administrators_controller.rb
index c72563c..97791c5 100644
--- a/app/controllers/administrators_controller.rb
+++ b/app/controllers/administrators_controller.rb
@@ -1,120 +1,86 @@
class AdministratorsController < ApplicationController
- before_filter :require_administrator
- before_filter :require_users_permission, :only => [ :destroy, :new, :create, :index ]
+ before_filter :require_administrator
+ before_filter :require_users_permission, :only => [ :destroy, :new, :create, :index ]
- def index
- @admins = Administrator.find(:all)
+ def index
+ @admins = Administrator.find(:all)
+ end
- respond_to do |format|
- format.html # index.html.erb
- format.xml { render :xml => @admins }
- end
- end
+ def show
+ @admin = Administrator.find(params[:id])
+ @admin = current_user if @admin == nil
+ end
- def show
- @admin = Administrator.find(params[:id])
- @admin = current_user if @admin == nil
- respond_to do |format|
- format.html # show.html.erb
- format.xml { render :xml => @admin }
- end
- end
+ def new
+ @admin = Administrator.new
+ end
- def new
- @admin = Administrator.new
+ def edit
+ @admin = Administrator.find(params[:id])
+ end
- respond_to do |format|
- format.html # new.html.erb
- format.xml { render :xml => @admin }
- end
- end
+ def create
+ @admin = Administrator.new(params[:administrator])
+ success = @admin.save
- def edit
- @admin = Administrator.find(params[:id])
+ if success
+ grant_permissions(params[:permission])
+ flash[:notice] = t:User_created
+ redirect_to(administrators_path)
+ else
+ render :action => "new"
end
+ end
- def create
- @admin = Administrator.new(params[:administrator])
- success = @admin.save
+ def update
+ @admin = Administrator.find(params[:id])
- if success && params.key?(:permission)
- params[:permission].each_key do |club_id|
- permissions = params[:permission][club_id]
- current_perms = @admin.permissions_for Club.find(club_id)
- permissions.each_key do |perm|
- if !current_perms.include? perm
- np = Permission.new
- np.club_id = club_id.to_i
- np.user = @admin
- np.permission = perm
- np.save!
- end
- end
- end
- end
-
- respond_to do |format|
- if success
- flash[:notice] = t:User_created
- format.html { redirect_to(administrators_path) }
- format.xml { render :xml => @admin, :status => :created, :location => @admin }
- else
- format.html { render :action => "new" }
- format.xml { render :xml => @admin.errors, :status => :unprocessable_entity }
- end
- end
+ if current_user.users_permission?
+ revoke_other_permissions_than(params[:permission])
+ grant_permissions(params[:permission])
end
- def update
- @admin = Administrator.find(params[:id])
+ if @admin.update_attributes(params[:administrator])
+ flash[:notice] = t(:User_updated)
+ redirect_to(@admin)
+ else
+ render :action => "edit"
+ end
+ end
- if current_user.users_permission?
- # Check all existing permissions to see if we should keep them
- if [email protected]?
- @admin.permissions.each do |p|
- c_id = p.club_id.to_s
- if !params.key?(:permission) || !params[:permission].key?(c_id) || !params[:permission][c_id].key?(p.permission)
- p.destroy
- end
- end
- end
+ def destroy
+ @admin = User.find(params[:id])
+ @admin.destroy
+ redirect_to(administrators_path)
+ end
- if params.key? :permission
- params[:permission].each_key do |club_id|
- permissions = params[:permission][club_id]
- current_perms = @admin.permissions_for Club.find(club_id)
- permissions.each_key do |perm|
- if !current_perms.include? perm
- np = Permission.new
- np.club_id = club_id.to_i
- np.user = @admin
- np.permission = perm
- np.save!
- end
- end
- end
- end
- end
+ private
- respond_to do |format|
- if @admin.update_attributes(params[:administrator])
- flash[:notice] = t(:User_updated)
- format.html { redirect_to(@admin) }
- format.xml { head :ok }
- else
- format.html { render :action => "edit" }
- format.xml { render :xml => @admin.errors, :status => :unprocessable_entity }
+ def grant_permissions(perms)
+ return if perms.blank?
+ perms.each_key do |club_id|
+ permissions = perms[club_id]
+ current_perms = @admin.permissions_for Club.find(club_id)
+ permissions.each_key do |perm|
+ if !current_perms.include? perm
+ np = Permission.new
+ np.club_id = club_id.to_i
+ np.user = @admin
+ np.permission = perm
+ np.save!
end
end
end
+ end
- def destroy
- @admin = User.find(params[:id])
- @admin.destroy
-
- respond_to do |format|
- format.html { redirect_to(administrators_path) }
- format.xml { head :ok }
+ def revoke_other_permissions_than(perms)
+ if [email protected]?
+ @admin.permissions.each do |p|
+ c_id = p.club_id.to_s
+ if perms.blank? || !perms.key?(c_id) || !perms[c_id].key?(p.permission)
+ p.destroy
+ end
end
end
end
+end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index a22d331..166d356 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,207 +1,208 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
+ export: export
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
Reset_password: Reset password
Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
No_user_found: No user with that email address or login could be found.
Password_updated: Password has been updated.
Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
Password_reset_descr: Type in your login name (as an administrator), or your email address.
Request_password_reset: Reset password
Forgot_password: Forgot your password?
activerecord:
messages:
in_future: in the future
diff --git a/test/integration/administrator_test.rb b/test/integration/administrator_test.rb
new file mode 100644
index 0000000..039dc65
--- /dev/null
+++ b/test/integration/administrator_test.rb
@@ -0,0 +1,75 @@
+require 'test_helper'
+
+class AdministratorTest < ActionController::IntegrationTest
+ def setup
+ create_club_and_admin
+ @other_club = Factory(:club)
+ end
+
+ test "grant all permissions" do
+ log_in_as_admin
+ click_link "Users"
+ click_link @admin.login
+ click_link "Edit"
+ cid = @other_club.id.to_s
+ %w[read edit delete graduations payments export].each do |perm|
+ check "permission_#{cid}_#{perm}"
+ end
+ click_button "Save"
+
+ assert_contain Regexp.new("#{@other_club.name}:\\s+Delete, Edit, Export, Graduations, Payments, Read", Regexp::MULTILINE)
+ end
+
+ test "revoke all permissions" do
+ log_in_as_admin
+ click_link "Users"
+ click_link @admin.login
+ click_link "Edit"
+ cid = @club.id.to_s
+ %w[read edit delete graduations payments export].each do |perm|
+ uncheck "permission_#{cid}_#{perm}"
+ end
+ click_button "Save"
+
+ assert_not_contain @club.name
+ end
+
+ test "grant read" do grant_one('read') ; end
+ test "grant edit" do grant_one('edit') ; end
+ test "grant delete" do grant_one('delete') ; end
+ test "grant payments" do grant_one('payments') ; end
+ test "grant graduations" do grant_one('graduations') ; end
+ test "grant export" do grant_one('export') ; end
+
+ test "revoke read" do revoke_one('read') ; end
+ test "revoke edit" do revoke_one('edit') ; end
+ test "revoke delete" do revoke_one('delete') ; end
+ test "revoke payments" do revoke_one('payments') ; end
+ test "revoke graduations" do revoke_one('graduations') ; end
+ test "revoke export" do revoke_one('export') ; end
+
+ private
+ def grant_one(perm)
+ log_in_as_admin
+ click_link "Users"
+ click_link @admin.login
+ click_link "Edit"
+ cid = @other_club.id.to_s
+ check "permission_#{cid}_#{perm}"
+ click_button "Save"
+
+ assert_contain Regexp.new("#{@other_club.name}:\\s+#{perm.titlecase}[^,]", Regexp::MULTILINE)
+ end
+
+ def revoke_one(perm)
+ log_in_as_admin
+ click_link "Users"
+ click_link @admin.login
+ click_link "Edit"
+ cid = @club.id.to_s
+ uncheck "permission_#{cid}_#{perm}"
+ click_button "Save"
+ perms = %w[read edit delete graduations payments export].sort - [ perm ]
+ assert_contain Regexp.new("#{@club.name}:\\s+#{perms.join(", ").titlecase}[^,]", Regexp::MULTILINE)
+ end
+end
|
calmh/Register
|
ffecfae2c88218ab1234b5274598cbaca2d0c067
|
Factory:ize integration tests.
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index b1242aa..61d0547 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,160 +1,171 @@
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class SiteSettings
def self.get_setting(setting)
s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
return "" if s == nil
return s.value
end
def self.set_setting(setting, value)
s = ConfigurationSetting.find(:first, :conditions => { :setting => setting })
if s == nil
s = ConfigurationSetting.new
s.setting = setting
end
s.value = value
s.save!
end
def self.site_name
get_setting(:site_name)
end
def self.site_name=(value)
set_setting(:site_name, value)
end
def self.site_theme
get_setting(:site_theme)
end
def self.site_theme=(value)
set_setting(:site_theme, value)
end
end
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user
before_filter :set_locale
protect_from_forgery # :secret => '4250e2ff2a2308b6668755ef76677cbb'
+ before_filter :require_site_permission, :only => [ :edit_site_settings, :update_site_settings ]
def set_locale
session[:locale] = params[:locale] if params[:locale] != nil
I18n.locale = session[:locale] if session[:locale] != nil
end
def edit_site_settings
- @available_themes = Dir.entries("public/stylesheets/themes").select { |d| !d.starts_with? '.' }.sort
+ begin
+ @available_themes = Dir.entries("public/stylesheets/themes").select { |d| !d.starts_with? '.' }.sort
+ rescue Exception => e
+ @available_themes = []
+ end
end
def update_site_settings
SiteSettings.site_name = params[:site_name]
SiteSettings.site_theme = params[:site_theme]
expire_fragment('layout_header')
flash[:notice] = t(:Site_settings_updated)
redirect_to :controller => 'application', :action => 'edit_site_settings'
end
def validate
require_administrator end
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def denied
store_location
flash[:warning] = t(:Must_log_in)
current_user_session.destroy if current_user_session
redirect_to new_user_session_path
return false
end
def require_student_or_administrator
return denied unless current_user
return true
end
def require_administrator_or_self(student)
return denied unless current_user.type == 'Administrator' || current_user == student
return true
end
def require_administrator
return denied unless current_user && current_user.type == 'Administrator'
return true
end
def require_clubs_permission
return denied unless current_user
return denied unless current_user.clubs_permission?
return true
end
def require_groups_permission
return denied unless current_user
return denied unless current_user.groups_permission?
return true
end
def require_users_permission
return denied unless current_user
return denied unless current_user.users_permission?
return true
end
def require_mailing_lists_permission
return denied unless current_user
return denied unless current_user.mailinglists_permission?
return true
end
+ def require_site_permission
+ return denied unless current_user
+ return denied unless current_user.site_permission?
+ return true
+ end
+
def require_export_permission(club)
return denied unless current_user
return denied unless current_user.export_permission?(club)
return true
end
def require_no_user
if current_user
store_location
redirect_to current_user
return false
end
return true
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
def get_default(key)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
return val.value if val != nil
return nil
end
def set_default(key, value)
val = DefaultValue.find(:first, :conditions => { :user_id => current_user.id, :key => key })
if val == nil
val = DefaultValue.new
val.user_id = current_user.id
val.key = key
end
val.value = value
val.save!
end
end
diff --git a/app/helpers/students_helper.rb b/app/helpers/students_helper.rb
index 75fcda8..3a87c16 100644
--- a/app/helpers/students_helper.rb
+++ b/app/helpers/students_helper.rb
@@ -1,10 +1,11 @@
module StudentsHelper
def format_zipcode(zipcode)
+ return nil if zipcode.blank?
zipcode.sub!(" ", "")
if zipcode =~ /^(\d\d\d)(\d\d)$/
return $1 + " " + $2
else
return zipcode
end
end
end
diff --git a/config/locales/en.yml b/config/locales/en.yml
index a769f7c..a22d331 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,198 +1,207 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
- Logout: Logout
+ Logout: Log out
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
- Edit_Site: Edit Site Settings
+ Edit_Site: Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
Body_text: Body text
Send: Send
Subject: Subject
From: From
Back: Back
Message_sent_to: Message sent to
Couldnt_send_to: Couldn't send to
because_no_email: because they don't have an email address.
+ Reset_password: Reset password
+ Mailed_reset_instruction: Instructions for resetting your password has been sent. Please check your email.
+ No_user_found: No user with that email address or login could be found.
+ Password_updated: Password has been updated.
+ Could_not_load_account: We could not load our account. Please try again, or copy and paste the URL from the mail to your browser.
+ Password_reset_descr: Type in your login name (as an administrator), or your email address.
+ Request_password_reset: Reset password
+ Forgot_password: Forgot your password?
+
activerecord:
messages:
in_future: in the future
diff --git a/test/integration/graduations_test.rb b/test/integration/graduations_test.rb
index 05c9a6d..405c042 100644
--- a/test/integration/graduations_test.rb
+++ b/test/integration/graduations_test.rb
@@ -1,100 +1,116 @@
require 'test_helper'
class GraduationsTest < ActionController::IntegrationTest
- fixtures :all
-
- test "graduation on a single student" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
-
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
-
- click_link "Amalia Gustavsson"
- click_link "Graderingar"
- select "Qi Gong"
- select "Gul II"
- fill_in "Instruktör", :with => "Name of Instructor"
- fill_in "Examinator", :with => "Name of Examiner"
- select "2009"
- select "Oktober"
- select "15"
- click_button "Spara"
-
- click_link "Klubbar"
- click_link "Brålanda"
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
- assert_contain "Gul II (Qi Gong)"
-
- click_link "Amalia Gustavsson"
- click_link "Graderingar"
- select "Kung Fu"
- select "Röd II"
- fill_in "Instruktör", :with => "Name of Instructor"
- fill_in "Examinator", :with => "Name of Examiner"
- select "2009"
- select "Oktober"
- select "20"
- click_button "Spara"
-
- click_link "Klubbar"
- click_link "Brålanda"
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
- assert_contain "Gul II (Qi Gong)"
-
- click_link "Amalia Gustavsson"
- click_link "Graderingar"
- select "Kung Fu"
- select "Grön II"
- fill_in "Instruktör", :with => "Name of Instructor"
- fill_in "Examinator", :with => "Name of Examiner"
- select "2009"
- select "Oktober"
- select "25"
- click_button "Spara"
-
- click_link "Klubbar"
- click_link "Brålanda"
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
- assert_contain "Gul II (Qi Gong)"
- end
-
- test "graduation on multiple students" do
- log_in
- click_link "Sök tränande"
- check "Brålanda"
- uncheck "Edsvalla"
- uncheck "Frillesås"
- uncheck "Nybro"
- uncheck "Tandsbyn"
- uncheck "Vallåkra"
- click_button "Sök"
-
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
-
- check "selected_students_25"
- check "selected_students_26"
- check "selected_students_27"
- click_button "Registrera gradering"
-
- select "Kung Fu"
- select "Gul II"
- fill_in "Instruktör", :with => "Name of Instructor"
- fill_in "Examinator", :with => "Name of Examiner"
- select "2009"
- select "Oktober"
- select "15"
- click_button "Spara"
-
- click_link "Klubbar"
- click_link "Brålanda"
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
- assert_contain "Gul II (Kung Fu)"
- end
+ def setup
+ create_club_and_admin
+
+ @categories = 4.times.map { Factory(:grade_category) }
+ @grades = 10.times.map { Factory(:grade) }
+ @students = 5.times.map { Factory(:student, :club => @club, :main_interest => @categories[0]) }
+ end
+
+ test "should display graduation on club page" do
+ Factory(:graduation, :student => @students[0], :grade => @grades[0], :grade_category => @categories[0])
+ category = @categories[0].category
+ grade = @grades[0].description
+
+ log_in_as_admin
+ click_link @club.name
+
+ assert_contain @students[0].name
+ assert_contain "#{grade} (#{category})"
+ end
+
+ test "should display latest graduation on club page" do
+ Factory(:graduation, :student => @students[0], :grade => @grades[0], :grade_category => @categories[0], :graduated => 6.months.ago)
+ Factory(:graduation, :student => @students[0], :grade => @grades[1], :grade_category => @categories[0], :graduated => 2.months.ago)
+ category = @categories[0].category
+ grade = @grades[1].description
+
+ log_in_as_admin
+ click_link @club.name
+
+ assert_contain @students[0].name
+ assert_contain "#{grade} (#{category})"
+ end
+
+ test "should display graduation with same category as main interest, even if earlier, on club page" do
+ Factory(:graduation, :student => @students[0], :grade => @grades[0], :grade_category => @categories[0], :graduated => 6.months.ago)
+ Factory(:graduation, :student => @students[0], :grade => @grades[1], :grade_category => @categories[1], :graduated => 2.months.ago)
+ category = @categories[0].category
+ grade = @grades[0].description
+
+ log_in_as_admin
+ click_link @club.name
+
+ assert_contain @students[0].name
+ assert_contain "#{grade} (#{category})"
+ end
+
+ test "should display graduation on student page" do
+ Factory(:graduation, :student => @students[0], :grade => @grades[0], :grade_category => @categories[0])
+ category = @categories[0].category
+ grade = @grades[0].description
+
+ log_in_as_admin
+ click_link @club.name
+
+ click_link @students[0].name
+ assert_contain grade
+ assert_contain category
+ end
+
+ test "should register graduation on a single student" do
+ category = @categories[0].category
+ grade = @grades[0].description
+
+ log_in_as_admin
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Graduations"
+ select category
+ select grade
+ fill_in "Instructor", :with => "Name of Instructor"
+ fill_in "Examiner", :with => "Name of Examiner"
+ select "2009"
+ select "October"
+ select "15"
+ click_button "Save"
+
+ click_link @club.name
+ assert_contain @students[0].name
+ assert_contain "#{grade} (#{category})"
+ end
+
+ test "should register graduation on multiple students" do
+ category = @categories[0].category
+ grade = @grades[0].description
+ graduated = @students[1..3]
+
+ log_in_as_admin
+ click_link @club.name
+
+ graduated.each do |s|
+ check "selected_students_#{s.id}"
+ end
+ click_button "Register graduation"
+
+ select category
+ select grade
+ fill_in "Instructor", :with => "Name of Instructor"
+ fill_in "Examiner", :with => "Name of Examiner"
+ select "2009"
+ select "October"
+ select "15"
+ click_button "Save"
+
+ click_link "Clubs"
+ click_link @club.name
+ graduated.each do |s|
+ click_link s.name
+ assert_contain grade
+ assert_contain category
+ click_link @club.name
+ end
+ end
end
diff --git a/test/integration/groups_test.rb b/test/integration/groups_test.rb
index fa35b15..64d8c18 100644
--- a/test/integration/groups_test.rb
+++ b/test/integration/groups_test.rb
@@ -1,23 +1,58 @@
require 'test_helper'
class GroupsTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
- test "check groups" do
- log_in
- click_link "Grupper"
+ @admin.groups_permission = true
+ @admin.save
- assert_contain "Elever"
- assert_contain /[^0-9.]10[^0-9.]/
- assert_contain "Instruktörer"
- assert_contain "Nyregistrerad"
- click_link "Nyregistrerad"
+ @groups = 4.times.map { Factory(:group) }
+ @students = 5.times.map { Factory(:student) }
- select "Elever"
- click_button "Spara"
+ @member_group = @groups[0]
+ @other_group = @groups[1]
+ @students.each do |s|
+ s.groups << @member_group
+ s.save
+ end
+ end
- assert_contain "Elever"
- assert_contain /[^0-9.]13[^0-9.]/
- assert_not_contain "Nyregistrerad"
- end
+ test "groups should be displayed on the groups page" do
+ log_in_as_admin
+ click_link "Groups"
+
+ @groups.each do |group|
+ assert_contain group.identifier
+ end
+ end
+
+ test "number of members should be displayed on the groups page" do
+ log_in_as_admin
+ click_link "Groups"
+
+ # Look for group name, followed by some text, then the number of members.
+ assert_contain Regexp.new("#{@member_group.identifier}[^0-9]+\\b#{@students.length}\\b", Regexp::MULTILINE)
+ end
+
+ test "members should be moved to another group when merged" do
+ log_in_as_admin
+ click_link "Groups"
+ click_link @member_group.identifier
+ select @other_group.identifier
+ click_button "Save"
+
+ # Look for group name, followed by some text, then the number of members.
+ assert_contain Regexp.new("#{@other_group.identifier}[^0-9]+\\b#{@students.length}\\b", Regexp::MULTILINE)
+ end
+
+ test "original group should be destroyed when merged" do
+ log_in_as_admin
+ click_link "Groups"
+ click_link @member_group.identifier
+ select @other_group.identifier
+ click_button "Save"
+
+ assert_not_contain @member_group.identifier
+ end
end
diff --git a/test/integration/locale_test.rb b/test/integration/locale_test.rb
new file mode 100644
index 0000000..232cf64
--- /dev/null
+++ b/test/integration/locale_test.rb
@@ -0,0 +1,27 @@
+require 'test_helper'
+
+class LocaleTest < ActionController::IntegrationTest
+ test "locale should be taken from parameter, swedish" do
+ visit "/?locale=sv"
+ assert_contain "Logga in"
+ end
+
+ test "locale should be taken from parameter, english" do
+ visit "/?locale=en"
+ assert_contain "Log in"
+ end
+
+ test "locale should stick in session, swedish" do
+ visit "/?locale=sv"
+ assert_contain "Logga in"
+ visit "/"
+ assert_contain "Logga in"
+ end
+
+ test "locale should stick in session, english" do
+ visit "/?locale=en"
+ assert_contain "Log in"
+ visit "/"
+ assert_contain "Log in"
+ end
+end
diff --git a/test/integration/mailing_list_test.rb b/test/integration/mailing_list_test.rb
index 02f9cb9..ce41672 100644
--- a/test/integration/mailing_list_test.rb
+++ b/test/integration/mailing_list_test.rb
@@ -1,67 +1,111 @@
require 'test_helper'
class MailingListTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
- test "check list och mailing lists" do
- log_in
- click_link "Epostlistor"
+ @admin.mailinglists_permission = true
+ @admin.save
- assert_contain "[email protected]"
- click_link "Ny epostlista"
+ @mailing_lists = 4.times.map { Factory(:mailing_list) }
+ @students = 5.times.map { Factory(:student) }
- fill_in "Epostadress", :with => "[email protected]"
- fill_in "Förklaring", :with => "En testlista"
- fill_in "Säkerhet", :with => "public"
- click_button "Spara"
+ @member_list = @mailing_lists[0]
+ @students.each do |s|
+ s.mailing_lists << @member_list
+ s.save
+ end
+ end
- assert_contain "[email protected]"
- assert_contain "En testlista"
- click_link "[email protected]"
+ test "mailing lists should be displayed on the list page" do
+ log_in_as_admin
+
+ click_link "Mailing lists"
+
+ @mailing_lists.each do |m|
+ assert_contain m.email
+ assert_contain m.description
+ end
+ end
+
+ test "should create new mailing list" do
+ log_in_as_admin
- assert_contain "Redigera epostlista"
- assert_contain "Radera"
- click_link "Radera"
+ click_link "Mailing lists"
+ click_link "New mailing list"
+
+ fill_in "Email", :with => "[email protected]"
+ fill_in "Description", :with => "A test list"
+ fill_in "Security", :with => "public"
+
+ click_button "Save"
+ click_link "Mailing lists"
assert_contain "[email protected]"
- assert_not_contain "[email protected]"
+ assert_contain "A test list"
end
- test "email address must be unique" do
- log_in
- click_link "Epostlistor"
+ test "should delete a mailing list" do
+ log_in_as_admin
- assert_contain "[email protected]"
- click_link "Ny epostlista"
+ click_link "Mailing lists"
+ click_link @mailing_lists[0].email
+ click_link "Destroy"
+
+ click_link "Mailing lists"
+ assert_not_contain @mailing_lists[0].email
+ end
- fill_in "Epostadress", :with => "[email protected]"
- fill_in "Förklaring", :with => "En testlista"
- fill_in "Säkerhet", :with => "public"
- click_button "Spara"
+ test "should not be able to create a new mailing list with non-unique email" do
+ log_in_as_admin
- assert_contain "upptagen"
+ click_link "Mailing lists"
+ click_link "New mailing list"
+
+ fill_in "Email", :with => @mailing_lists[0].email
+ fill_in "Description", :with => "A test list"
+ fill_in "Security", :with => "public"
+
+ click_button "Save"
+ assert_contain "taken"
end
+ test "mailing list should show members" do
+ log_in_as_admin
+
+ click_link "Mailing lists"
+ click_link @member_list.email
+
+ @students.each do |s|
+ assert_contain s.name
+ end
+ end
+
test "remove student from mailing list" do
- log_in
- click_link "Epostlistor"
- click_link "[email protected]"
+ log_in_as_admin
+
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
- assert_contain "Amalia"
+ uncheck @member_list.description
+ click_button "Save"
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Amalia Gustavsson"
- click_link "Redigera"
+ assert_not_contain @member_list.description
+ end
- uncheck "Instructors"
- click_button "Spara"
+ test "remove student from mailing list, and verify this on the membership page" do
+ log_in_as_admin
- assert_not_contain "Instructors"
+ click_link @club.name
+ click_link @students[0].name
+ click_link "Edit"
- click_link "Epostlistor"
- click_link "[email protected]"
+ uncheck @member_list.description
+ click_button "Save"
- assert_not_contain "Amalia"
+ click_link "Mailing lists"
+ click_link @member_list.email
+ assert_not_contain @students[0].name
end
end
diff --git a/test/integration/payments_test.rb b/test/integration/payments_test.rb
index affe2a8..8799605 100644
--- a/test/integration/payments_test.rb
+++ b/test/integration/payments_test.rb
@@ -1,23 +1,57 @@
require 'test_helper'
class PaymentsTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
+ @student = Factory(:student, :club => @club)
+ end
- test "register payment" do
- log_in
- click_link "Brålanda"
- click_link "Amalia Gustavsson"
- assert_contain "Ingen inbetalning registrerad"
- click_link "Inbetalningar"
- fill_in "Belopp", :with => "499,50"
- fill_in "Förklaring", :with => "VT 2009"
+ test "no payment by default" do
+ log_in_as_admin
+ click_link @club.name
+ click_link @student.name
+ assert_contain "No payment"
+ end
+
+ test "payment should be registered and displayed" do
+ log_in_as_admin
+ click_link @club.name
+ click_link @student.name
+ click_link "Payments"
+ fill_in "Amount", :with => "499.50"
+ fill_in "Description", :with => "Spring 2010"
select "December"
select "23"
select "2009"
- click_button "Spara"
- click_link "Visa"
- assert_contain "499"
- assert_contain "VT 2009"
- click_link "Brålanda"
+ click_button "Save"
+ click_link "Show"
+ assert_contain /Amount:\s+499.5/m
+ assert_contain /Description:\s+Spring 2010/m
+ end
+
+ test "latest payment should be displayed" do
+ log_in_as_admin
+ click_link @club.name
+ click_link @student.name
+
+ click_link "Payments"
+ fill_in "Amount", :with => "499.50"
+ fill_in "Description", :with => "Spring 2010"
+ select "December"
+ select "23"
+ select "2009"
+ click_button "Save"
+
+ click_link "Payments"
+ fill_in "Amount", :with => "199"
+ fill_in "Description", :with => "Autumn 2009"
+ select "August"
+ select "20"
+ select "2009"
+ click_button "Save"
+
+ click_link "Show"
+ assert_contain /Amount:\s+499.5/m
+ assert_contain /Description:\s+Spring 2010/m
end
end
diff --git a/test/integration/permission_test.rb b/test/integration/permission_test.rb
index ab534b8..20303b3 100644
--- a/test/integration/permission_test.rb
+++ b/test/integration/permission_test.rb
@@ -1,176 +1,158 @@
require 'test_helper'
class PermissionTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
+ end
test "blank log in goes nowhere" do
- visit "/"
- assert_contain "måste logga in"
- click_button "Logga in"
- assert_contain "Logga in"
+ visit "/?locale=en"
+ assert_contain "must log in"
+ click_button "Log in"
+
+ assert_contain "invalid"
+ assert_contain "Log in"
end
test "failed log in goes nowhere" do
- visit "/"
- assert_contain "måste logga in"
- fill_in "Användarnamn", :with => "test"
- fill_in "Lösenord", :with => "abc123"
- click_button "Logga in"
-
- assert_contain "Logga in"
+ visit "/?locale=en"
+ assert_contain "must log in"
+ fill_in "Login", :with => "test"
+ fill_in "Password", :with => "abc123"
+ click_button "Log in"
+
+ assert_contain "invalid"
+ assert_contain "Log in"
end
- test "log in by email works" do
- visit "/"
- assert_contain "måste logga in"
- fill_in "Användarnamn", :with => "[email protected]"
- fill_in "Lösenord", :with => "admin"
- click_button "Logga in"
+ test "should be able to log in by email" do
+ visit "/?locale=en"
+ assert_contain "must log in"
+ fill_in "Login", :with => @admin.email
+ fill_in "Password", :with => "admin"
+ click_button "Log in"
- assert_contain "Logga ut"
+ assert_contain "Log out"
end
- test "try to log in and check clubs list" do
- log_in
-
- assert_contain "Logga ut"
- assert_contain "Klubbar"
- click_link "Nybro"
- assert_contain " 1 tränande"
- assert_contain "Svante Jansson"
- assert_contain "Val för Nybro"
- assert_contain "Ny tränande"
+ test "student should be able to log in by email" do
+ student = Factory(:student, :club => @club, :password => 'password', :password_confirmation => 'password')
+ visit "/?locale=en"
+ fill_in "Login", :with => student.email
+ fill_in "Password", :with => "password"
+ click_button "Log in"
+ assert_contain "Home Phone"
+ end
+
+ test "should only see clubs with permissions" do
+ @other_club = Factory(:club)
+ log_in_as_admin
+
+ click_link "Clubs"
+ assert_contain @club.name
+ assert_not_contain @other_club.name
end
- test "verify no clubs permission" do
- log_in
+ test "should see groups link" do
+ log_in_as_admin
- assert_contain "Klubbar"
- assert_contain "Grupper"
- assert_contain "Användare"
- assert_contain "Sök tränande"
- assert_contain "Ny klubb"
- click_link "Användarprofil"
+ assert_contain "Groups"
+ end
- click_link "Redigera"
+ test "should see mailing lists link" do
+ log_in_as_admin
- uncheck "administrator[clubs_permission]"
- click_button "Spara"
+ assert_contain "Mailing Lists"
+ end
- assert_not_contain "Redigera klubbar:"
- assert_contain /Nybro:[^:]+Redigera/m
- # assert_not_contain /Edsvalla:[^:]+Graderingar/m
- click_link "Klubbar"
+ test "should see site settings link" do
+ log_in_as_admin
- assert_not_contain "Ny klubb"
- assert_not_contain "Sök tränande"
- # click_link "Edsvalla"
- # assert_contain " 2 tränande"
- # assert_have_no_selector "#bulk_graduations"
-
- click_link "Klubbar"
- click_link "Nybro"
- assert_have_selector "#bulk_graduations"
- end
+ assert_contain "Site Settings"
+ end
- test "verify no users permission" do
- log_in
+ test "should see users settings link" do
+ log_in_as_admin
- assert_contain "Klubbar"
- assert_contain "Grupper"
- assert_contain "Användare"
- assert_contain "Sök tränande"
- assert_contain "Ny klubb"
- click_link "Användarprofil"
+ assert_contain "Users"
+ end
- click_link "Redigera"
+ test "should not see links we don't have access to" do
+ @admin.users_permission = false
+ @admin.site_permission = false
+ @admin.groups_permission = false
+ @admin.mailinglists_permission = false
+ @admin.save
- uncheck "administrator[users_permission]"
- click_button "Spara"
+ log_in_as_admin
- assert_not_contain "Redigera användare:"
- assert_contain /Redigera grupper:\s+Ja/m
- assert_not_contain /Användare\W/
- click_link "Redigera"
+ # Need to check for absence of link "Groups", not just the string
+ # assert_not_contain "Groups"
+ assert_not_contain "Site Settings"
+ assert_not_contain "Mailing Lists"
+ assert_not_contain "Users"
+ end
- assert_not_contain "Globala rättigheter"
- assert_not_contain "Rättigheter per klubb"
-
- click_link "Klubbar"
- assert_contain "Nybro"
-
- visit "/administrators"
- assert_contain "måste logga in"
- end
+ test "should not see edit club link" do
+ @admin.clubs_permission = false
+ @admin.save
- test "verify no groups permission" do
- log_in
+ log_in_as_admin
+ click_link @club.name
+ assert_not_contain "Edit"
+ end
- assert_contain "Klubbar"
- assert_contain "Grupper"
- assert_contain "Användare"
- assert_contain "Sök tränande"
- assert_contain "Ny klubb"
- click_link "Användarprofil"
+ test "should not be able to access site settings" do
+ @admin.site_permission = false
+ @admin.save
- click_link "Redigera"
+ log_in_as_admin
+ visit "/edit_site_settings"
+ assert_contain "must log in"
+ end
- uncheck "administrator[groups_permission]"
- click_button "Spara"
-
- assert_not_contain "Redigera grupper:"
- assert_not_contain "Grupper"
-
- click_link "Klubbar"
- assert_contain "Nybro"
+ test "should not be able to access groups" do
+ @admin.groups_permission = false
+ @admin.save
+ log_in_as_admin
visit "/groups"
- assert_contain "måste logga in"
- end
+ assert_contain "must log in"
+ end
- test "add and remove club permissions" do
- log_in
+ test "should not be able to access mailing lists" do
+ @admin.mailinglists_permission = false
+ @admin.save
- click_link "Användare"
- click_link "ci"
+ log_in_as_admin
+ visit "/mailing_lists"
+ assert_contain "must log in"
+ end
- assert_contain /Edsvalla:\s+Radera, Redigera, Inbetalningar, Se/m
- assert_not_contain "Nybro"
+ test "should not be able to access users" do
+ @admin.users_permission = false
+ @admin.save
- click_link "Redigera"
- uncheck "permission[8][edit]"
- uncheck "permission[8][delete]"
- uncheck "permission[8][payments]"
- check "permission[9][read]"
- check "permission[9][edit]"
- check "permission[9][payments]"
- click_button "Spara"
+ log_in_as_admin
+ visit "/administrators"
+ assert_contain "must log in"
+ end
- assert_contain /Edsvalla:\s+Se/m
- assert_contain /Nybro:\s+Redigera, Inbetalningar, Se/m
- end
+ test "should not be able to edit club" do
+ @admin.clubs_permission = false
+ @admin.save
- test "ci permissions" do
- log_in_as_ci
- assert_contain "Edsvalla"
- # assert_not_contain "Val"
+ log_in_as_admin
+ visit "/clubs/" + @club.id.to_s + "/edit"
+ assert_contain "must log in"
+ end
- click_link "Användarprofil"
- assert_not_contain "Ny användare"
- end
+ test "should not be able to export club data" do
+ Permission.find(:all, :conditions => {:permission => 'export'}).each { |p| p.destroy }
+ log_in_as_admin
- test "ci does not have access to export" do
- log_in_as_ci
- click_link "Edsvalla"
- assert_not_contain "Export"
- visit "/clubs/8/students.csv"
- assert_contain "logga in"
- end
+ visit "/clubs/" + @club.id.to_s + "/students.csv"
+ assert_contain "must log in"
+ end
- test "admin has access to export" do
- log_in
- click_link "Edsvalla"
- click_link "Exportera som CSV"
- assert_contain "first_name"
- end
end
diff --git a/test/integration/reset_password_test.rb b/test/integration/reset_password_test.rb
index 77a89d1..480333f 100644
--- a/test/integration/reset_password_test.rb
+++ b/test/integration/reset_password_test.rb
@@ -1,49 +1,50 @@
require 'test_helper'
class ResetPasswordTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
+ @student = Factory(:student, :email => "[email protected]")
+ end
test "verify redirect when logged in" do
- log_in
+ log_in_as_admin
visit "/password_resets/new"
- assert_contain "Användarprofil"
- assert_contain "Admin Istrator"
+ assert_contain "Profile"
+ assert_contain @admin.fname + " " + @admin.sname
end
test "verify reset with admin username" do
visit "/password_resets/new"
- fill_in "Användarnamn eller epostadress", :with => "admin"
- click_button "Ã
terställ lösenord"
- assert_contain "har skickats"
+ fill_in "Login or email", :with => "admin"
+ click_button "Reset password"
+ assert_contain "been sent"
end
test "verify reset with user email" do
visit "/password_resets/new"
- fill_in "Användarnamn eller epostadress", :with => "[email protected]"
- click_button "Ã
terställ lösenord"
- assert_contain "har skickats"
+ fill_in "Login or email", :with => @student.email
+ click_button "Reset password"
+ assert_contain "been sent"
end
test "verify setting new password for admin" do
- a = User.find_by_login("admin")
- a.reset_perishable_token!
- pt = a.perishable_token
+ @admin.reset_perishable_token!
+ pt = @admin.perishable_token
visit "/password_resets/#{pt}/edit"
- fill_in "Lösenord", :with => "password"
- fill_in "Upprepa lösenordet", :with => "password"
- click_button "Ã
terställ lösenord"
- assert_contain "har uppdaterats"
+ fill_in "Password", :with => "password"
+ fill_in "Confirm password", :with => "password"
+ click_button "Reset password"
+ assert_contain "updated"
end
test "verify setting new password for user" do
- a = User.find_by_email("[email protected]")
- a.reset_perishable_token!
- pt = a.perishable_token
+ @student.reset_perishable_token!
+ pt = @student.perishable_token
visit "/password_resets/#{pt}/edit"
- fill_in "Lösenord", :with => "password"
- fill_in "Upprepa lösenordet", :with => "password"
- click_button "Ã
terställ lösenord"
- assert_contain "har uppdaterats"
+ fill_in "Password", :with => "password"
+ fill_in "Confirm password", :with => "password"
+ click_button "Reset password"
+ assert_contain "updated"
end
end
diff --git a/test/integration/students_test.rb b/test/integration/students_test.rb
index bae0445..c8676a1 100644
--- a/test/integration/students_test.rb
+++ b/test/integration/students_test.rb
@@ -1,186 +1,157 @@
require 'test_helper'
-class GroupsTest < ActionController::IntegrationTest
- fixtures :all
-
- test "list students" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
-
- assert_contain "Amalia Gustavsson"
- assert_contain " 3 tränande"
- end
-
- test "new student with no info" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- click_button "Spara"
-
- assert_not_contain "skapats"
- assert_contain /tomt|saknas/
+class StudentsTest < ActionController::IntegrationTest
+ def setup
+ create_club_and_admin
+ @category = Factory(:grade_category)
+ @students = 10.times.map { Factory(:student, :club => @club) }
+ end
+
+ test "student page should show all students" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ @students.each do |s|
+ assert_contain s.name
+ end
+ assert_contain " #{@students.length} students"
end
- test "new student with no personal_number, corrected" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- select "Kung Fu"
- click_button "Spara"
+ test "should not create new blank student" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
- assert_not_contain "skapats"
- assert_contain /tomt|saknas/
+ click_button "Save"
- fill_in "Personnummer", :with => "19850203"
- click_button "Spara"
- assert_contain "skapats"
+ assert_not_contain "created"
+ assert_contain "can't be blank"
end
- test "new student with minimal info" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- select "Kung Fu"
- click_button "Spara"
+ test "should create new student with minimal info" do
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
- assert_contain "skapats"
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ select @category.category
+ click_button "Save"
- click_link "Klubbar"
- click_link "Brålanda"
-
- assert_contain " 4 tränande"
- assert_contain "Test Testsson"
+ assert_contain "created"
end
- test "new student in group" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- check "Elever"
- click_button "Spara"
- assert_contain "Elever"
-
- click_link "Klubbar"
- click_link "Brålanda"
-
- assert_contain " 4 tränande"
- assert_contain "Test Testsson"
-
- click_link "Grupper"
- click_link "Elever"
- assert_contain "Test Testsson"
- end
-
- test "new student in two groups" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- check "Elever"
- check "Instruktörer"
- click_button "Spara"
-
- assert_contain "Elever"
- assert_contain "Instruktörer"
-
- click_link "Klubbar"
- click_link "Brålanda"
-
- assert_contain " 4 tränande"
- assert_contain "Test Testsson"
-
- click_link "Grupper"
- click_link "Elever"
- assert_contain "Test Testsson"
-
- click_link "Grupper"
- click_link "Instruktör"
- assert_contain "Test Testsson"
+ test "should create a new student in x groups" do
+ @admin.groups_permission = true
+ @admin.save
+ all_groups = 4.times.map { Factory(:group) }
+ member_groups = all_groups[1..2]
+ non_member_groups = all_groups - member_groups
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ member_groups.each do |g|
+ check g.identifier
+ end
+ click_button "Save"
+ assert_contain "created"
+
+ member_groups.each do |g|
+ click_link "Groups"
+ click_link g.identifier
+ assert_contain "Test Testsson"
+ end
+
+ non_member_groups.each do |g|
+ click_link "Groups"
+ click_link g.identifier
+ assert_not_contain "Test Testsson"
+ end
end
- test "new student in two mailing lists" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- check "Everyone"
- check "Instructors"
- click_button "Spara"
-
- assert_contain "Everyone"
- assert_contain "Instructors"
-
- click_link "Epostlistor"
- click_link "[email protected]"
-
- assert_contain "Test Testsson"
-
- click_link "Epostlistor"
- click_link "[email protected]"
-
- assert_contain "Test Testsson"
+ test "should create a new student in x mailing lists" do
+ @admin.mailinglists_permission = true
+ @admin.save
+ all_lists = 4.times.map { Factory(:mailing_list) }
+ member_lists = all_lists[1..2]
+ non_member_lists = all_lists - member_lists
+
+ log_in_as_admin
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ member_lists.each do |m|
+ check m.description
+ end
+ click_button "Save"
+ assert_contain "created"
+
+ member_lists.each do |m|
+ click_link "Mailing Lists"
+ click_link m.email
+ assert_contain "Test Testsson"
+ end
+
+ non_member_lists.each do |m|
+ click_link "Mailing Lists"
+ click_link m.email
+ assert_not_contain "Test Testsson"
+ end
end
test "new student should join club mailing list per default" do
- log_in
- click_link "Klubbar"
- click_link "Brålanda"
- click_link "Ny tränande"
+ mailing_list = Factory(:mailing_list, :default => 1)
+ @admin.mailinglists_permission = true
+ @admin.save
+ log_in_as_admin
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- click_button "Spara"
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
- assert_contain "Brålanda-elever"
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ click_button "Save"
- click_link "Epostlistor"
- click_link "[email protected]"
+ click_link "Mailing Lists"
+ click_link mailing_list.email
assert_contain "Test Testsson"
end
test "new student should not join other club mailing list per default" do
- log_in
- click_link "Klubbar"
- click_link "Edsvalla"
- click_link "Ny tränande"
-
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Personnummer", :with => "19850203"
- click_button "Spara"
-
- assert_not_contain "Brålanda-elever"
-
- click_link "Epostlistor"
- click_link "[email protected]"
+ other_club = Factory(:club)
+ mailing_list = Factory(:mailing_list, :default => 1, :club => other_club)
+ @admin.mailinglists_permission = true
+ @admin.save
+ log_in_as_admin
+
+ click_link "Clubs"
+ click_link @club.name
+ click_link "New student"
+
+ fill_in "Name", :with => "Test"
+ fill_in "Surname", :with => "Testsson"
+ fill_in "Personal number", :with => "19850203"
+ click_button "Save"
+
+ click_link "Mailing Lists"
+ click_link mailing_list.email
assert_not_contain "Test Testsson"
end
end
diff --git a/test/integration/users_test.rb b/test/integration/users_test.rb
deleted file mode 100644
index a824146..0000000
--- a/test/integration/users_test.rb
+++ /dev/null
@@ -1,37 +0,0 @@
-require 'test_helper'
-
-class UsersTest < ActionController::IntegrationTest
- fixtures :all
-
- test "check groups" do
- log_in
- click_link "Användare"
- click_link "Ny användare"
- fill_in "Användarnamn", :with => "test"
- fill_in "Förnamn", :with => "Test"
- fill_in "Efternamn", :with => "Testsson"
- fill_in "Epostadress", :with => "[email protected]"
- fill_in "Lösenord", :with => "abc123"
- fill_in "Upprepa lösenordet", :with => "abc123"
- check "permission[8][read]"
- click_button "Spara"
-
- assert_contain "har skapats"
- assert_contain "Test Testsson"
-
- click_link "test"
-
- assert_contain /Edsvalla:\s+Se[^,]/m
- assert_not_contain "Brålanda"
- assert_not_contain "Nybro"
- end
-
- test "log in as student" do
- visit "/"
- fill_in "Användarnamn eller epostadress", :with => "[email protected]"
- fill_in "Lösenord", :with => "password"
- click_button "Logga in"
- assert_contain "Epostadress"
- assert_contain "Epostlistor"
- end
-end
diff --git a/test/integration/viewing_test.rb b/test/integration/viewing_test.rb
index 4ebaac3..1bf9aaa 100644
--- a/test/integration/viewing_test.rb
+++ b/test/integration/viewing_test.rb
@@ -1,66 +1,72 @@
require 'test_helper'
class ViewingTest < ActionController::IntegrationTest
- fixtures :all
+ def setup
+ create_club_and_admin
+ @admin.clubs_permission = true
+ @admin.save
+
+ @students = [
+ Factory(:student, :fname => "Aa", :sname => "Bb", :club => @club),
+ Factory(:student, :fname => "Bb", :sname => "Cc", :club => @club),
+ Factory(:student, :fname => "Cc", :sname => "Dd", :club => @club),
+ Factory(:student, :fname => "Dd", :sname => "Ee", :club => @club)
+ ]
+ @students.each do |s|
+ Factory(:payment, :student => s, :received => 14.months.ago)
+ end
+ @active_students = @students[1..2]
+ @active_students.each do |s|
+ Factory(:payment, :student => s, :received => 2.months.ago)
+ end
+ @inactive_students = @students - @active_students
+ end
test "verify student sorting" do
- log_in
+ log_in_as_admin
- click_link "Klubbar"
- click_link "Brålanda"
- assert_contain /Agaton.*Amalia.*Emma/m
+ click_link "Clubs"
+ click_link @club.name
+ assert_contain /Aa Bb.*Bb Cc.*Cc Dd.*Dd Ee/m
- click_link "Sök tränande"
- assert_contain /Baran.*Devin.*Edgar.*Marielle.*Nino.*Svante/m
+ click_link "Search Students"
+ assert_contain /Aa Bb.*Bb Cc.*Cc Dd.*Dd Ee/m
end
test "verify only active filtering" do
- log_in
+ log_in_as_admin
- click_link "Klubbar"
- click_link "Edsvalla"
- assert_contain "Baran"
- assert_contain "Razmus"
+ click_link "clubs"
+ click_link @club.name
+ @students.each do |s|
+ assert_contain s.name
+ end
check "a"
- click_button "Sök"
+ click_button "Search"
- assert_contain "Razmus"
- assert_not_contain "Baran"
+ @active_students.each do |s|
+ assert_contain s.name
+ end
+ @inactive_students.each do |s|
+ assert_not_contain s.name
+ end
- click_button "Sök"
+ click_button "Search"
- assert_contain "Razmus"
- assert_not_contain "Baran"
+ @active_students.each do |s|
+ assert_contain s.name
+ end
+ @inactive_students.each do |s|
+ assert_not_contain s.name
+ end
uncheck "a"
- click_button "Sök"
- assert_contain "Baran"
- assert_contain "Razmus"
- end
-
- test "verify student search" do
- log_in
-
- assert_contain "Klubbar"
- assert_contain "Grupper"
- assert_contain "Användare"
- assert_contain "Sök tränande"
- assert_contain "Ny klubb"
- click_link "Sök tränande"
- assert_contain " 13 tränande"
-
- select "Instruktörer"
- click_button "Sök"
- assert_contain " 2 tränande"
+ click_button "Search"
- check "a"
- click_button "Sök"
- assert_contain " 1 tränande"
-
- uncheck "a"
- click_button "Sök"
- assert_contain " 2 tränande"
+ @students.each do |s|
+ assert_contain s.name
+ end
end
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index f772be7..29ea377 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,60 +1,61 @@
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
#require 'authlogic/test_case'
require "webrat"
Webrat.configure do |config|
config.mode = :rails
end
class ActiveSupport::TestCase
# setup :activate_authlogic
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
# Every Active Record database supports transactions except MyISAM tables
# in MySQL. Turn off transactional fixtures in this case; however, if you
# don't care one way or the other, switching from MyISAM to InnoDB tables
# is recommended.
#
# The only drawback to using transactional fixtures is when you actually
# need to test transactions. Since your test is bracketed by a transaction,
# any transactions started in your code will be automatically rolled back.
self.use_transactional_fixtures = true
# Instantiated fixtures are slow, but give you @david where otherwise you
# would need people(:david). If you don't want to migrate your existing
# test cases which use the @david style and don't mind the speed hit (each
# instantiated fixtures translates to a database query per test method),
# then set this back to true.
self.use_instantiated_fixtures = false
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
-
- def log_in
- visit "/"
- fill_in "Användarnamn", :with => "admin"
- fill_in "Lösenord", :with => "admin"
- click_button "Logga in"
- end
-
- def log_in_as_ci
- visit "/"
- fill_in "Användarnamn", :with => "ci"
- fill_in "Lösenord", :with => "ci123"
- click_button "Logga in"
- end
+ def create_club_and_admin
+ @club = Factory(:club)
+ @admin = Factory(:administrator, :login => 'admin', :password => 'admin', :password_confirmation => 'admin')
+ %w[read edit delete graduations payments export].each do |perm|
+ Factory(:permission, :club => @club, :user => @admin, :permission => perm)
+ end
+ end
+
+ def log_in_as_admin
+ visit "/?locale=en"
+ fill_in "Login", :with => "admin"
+ fill_in "Password", :with => "admin"
+ uncheck "Remember me"
+ click_button "Log in"
+ end
end
diff --git a/test/unit/student_test.rb b/test/unit/student_test.rb
index a8c80a3..f9c4bd6 100644
--- a/test/unit/student_test.rb
+++ b/test/unit/student_test.rb
@@ -1,131 +1,135 @@
require 'test_helper'
class StudentTest < ActiveSupport::TestCase
def setup
Factory(:student, :personal_number => '19710730-3187')
@student = Factory(:student)
end
test "luhn calculation valid" do
@student.personal_number = "198002020710"
assert @student.luhn == 0
end
test "luhn calculation invalid" do
@student.personal_number = "198102020710"
assert @student.luhn != 0
end
test "personal number must be unique" do
@student.personal_number = "19710730-3187"
assert [email protected]?
end
test "autocorrection should do nothing with clearly invalid format" do
@student.personal_number = "abc123"
assert @student.personal_number == "abc123"
end
test "autocorrection should pass on correct format but unreasonable date" do
@student.personal_number = "20710730-3187"
assert @student.personal_number == "20710730-3187"
end
test "autocorrection should add century and dash" do
@student.personal_number = "7107303187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrection should add century" do
@student.personal_number = "710730-3187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrectionion should add dash" do
@student.personal_number = "197107303187"
assert @student.personal_number == "19710730-3187"
end
test "autocorrect should pass correct personal number" do
@student.personal_number = "19710730-3187"
assert @student.personal_number == "19710730-3187"
end
test "personal number must follow correct format" do
@student.personal_number = "abc123"
assert [email protected]?
end
test "personal number must not be too far in the future" do
@student.personal_number = "20550213-2490"
assert [email protected]?
end
if REQUIRE_PERSONAL_NUMBER
test "personal number cannot be nil" do
@student.personal_number = nil
assert [email protected]?
end
test "personal number must not be blank" do
@student.personal_number = ""
assert [email protected]?
end
test "century digits will be auto added" do
@student.personal_number = "550213-2490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "century digits and dash will be auto added" do
@student.personal_number = "5502132490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "dash will be auto added" do
@student.personal_number = "195502132490"
assert @student.personal_number == "19550213-2490"
assert @student.valid?
end
test "valid personal number should be accepted" do
@student.personal_number = "19550213-2490"
assert @student.valid?
end
if BIRTHDATE_IS_ENOUGH
test "valid birth date should be accepted" do
@student.personal_number = "19550213"
assert @student.valid?
end
else
test "only birth date should not be accepted" do
@student.personal_number = "19550213"
assert [email protected]?
end
end
end
test "gender should be set manually in lack of personal number" do
@student.personal_number = nil
@student.gender = "male"
assert @student.gender == "male"
@student.gender = "female"
assert @student.gender == "female"
end
test "gender should be set from personal number, male" do
@student.personal_number = "19550213-2490"
@student.gender = "female"
assert @student.gender == "male"
end
test "gender should be set from personal number, female" do
@student.personal_number = "19680614-5527"
@student.gender = "male"
assert @student.gender == "female"
end
+
+ test "current grade should be nil by default" do
+ assert @student.current_grade == nil
+ end
end
|
calmh/Register
|
8dcad72a7dc732326c63278a680225220e3f1945
|
Add seed data and more factories.
|
diff --git a/db/seeds.rb b/db/seeds.rb
new file mode 100644
index 0000000..c397878
--- /dev/null
+++ b/db/seeds.rb
@@ -0,0 +1,28 @@
+Factory(:configuration_setting, :setting => :site_theme, :value => 'djime-cerulean')
+
+admin = Factory(:administrator, :login => 'admin',
+ :password => 'admin', :password_confirmation => 'admin',
+ :groups_permission => true,
+ :mailinglists_permission => true,
+ :clubs_permission => true,
+ :users_permission => true,
+ :site_permission => true
+ )
+
+club = Factory(:club)
+10.times do
+ Factory(:student, :club => club)
+end
+
+%w[read edit delete graduations payments export].each do |perm|
+ Factory(:permission, :club => club, :user => admin, :permission => perm)
+end
+
+4.times do
+ Factory(:mailing_list)
+end
+
+4.times do
+ Factory(:group)
+end
+
diff --git a/test/factories.rb b/test/factories.rb
index 96f335e..f566d8f 100644
--- a/test/factories.rb
+++ b/test/factories.rb
@@ -1,93 +1,127 @@
def cached_association(key)
object = key.to_s.camelize.constantize.first
object ||= Factory(key)
end
Factory.sequence :pnumber do |n|
personal_number = '19800101-' + '%03d'%n
# Calculate valid check digit
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..13].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
check = (10 - sum) % 10
personal_number + check.to_s
end
Factory.define :grade_category do |c|
c.sequence(:category) { |n| "Category #{n}" }
end
Factory.define :grade do |c|
c.sequence(:level) { |n| n }
c.description { |g| "Grade #{g.level}" }
end
Factory.define :graduation do |f|
f.instructor "Instructor"
f.examiner "Examiner"
f.graduated Time.now
f.grade { cached_association(:grade) }
- f.grade_category { cached_association(:grade) }
+ f.grade_category { cached_association(:grade_category) }
f.student { cached_association(:grade) }
end
+Factory.define :group do |f|
+ f.sequence(:identifier) { |n| "Group #{n}" }
+ f.comments "An auto-created group"
+ f.default 0
+end
+
+Factory.define :groups_students do |f|
+ f.association :group
+ f.association :student
+end
+
+Factory.define :mailing_list do |f|
+ f.sequence(:email) { |n| "list#{n}@example.com" }
+ f.sequence(:description) { |n| "Mailing List #{n}" }
+ f.security "public"
+ f.default 0
+end
+
+Factory.define :mailing_lists_students do |f|
+ f.association :mailing_list
+ f.association :student
+end
+
+Factory.define :groups_students do |f|
+ f.association :group
+ f.association :student
+end
+
Factory.define :club do |c|
c.sequence(:name) {|n| "Club #{n}" }
end
Factory.define :board_position do |c|
c.position "Secretary"
end
Factory.define :club_position do |c|
c.position "Instructor"
end
Factory.define :title do |c|
c.title "Student"
c.level 1
end
Factory.define :payment do |c|
c.amount 700
c.received Time.now
c.description "Comment"
end
Factory.define :student do |s|
s.fname 'John'
s.sequence(:sname) {|n| "Doe_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) { |n| "person#{n}@example.com" }
s.personal_number { Factory.next(:pnumber) }
s.main_interest { cached_association(:grade_category) }
s.club { cached_association(:club) }
s.club_position { cached_association(:club_position) }
s.board_position { cached_association(:board_position) }
s.title { cached_association(:title) }
end
Factory.define :administrator do |s|
s.fname 'Admin'
s.sequence(:sname) {|n| "Istrator_#{n}" }
s.password "password"
s.password_confirmation "password"
s.sequence(:email) {|n| "admin#{n}@example.com" }
s.sequence(:login) {|n| "admin#{n}" }
- s.clubs_permission false
- s.users_permission false
- s.groups_permission false
- s.mailinglists_permission false
+ s.clubs_permission true
+ s.users_permission true
+ s.groups_permission true
+ s.mailinglists_permission true
+ s.site_permission true
end
Factory.define :permission do |p|
p.association :club
p.association :user, :factory => :administrator
p.permission "read"
end
+
+Factory.define :configuration_setting do |o|
+ o.setting "setting"
+ o.value "value"
+end
|
calmh/Register
|
7524eb211e3b12386d18741d8cf8165490eb0724
|
Converted form to Haml, corrected checkboxes.
|
diff --git a/app/views/students/_form.html.erb b/app/views/students/_form.html.erb
deleted file mode 100644
index a065d3b..0000000
--- a/app/views/students/_form.html.erb
+++ /dev/null
@@ -1,121 +0,0 @@
-<%= f.hidden_field :club_id, :class => 'text_field' %>
-
-<div class="group">
- <%= f.label :fname, t(:Groups), :class => :label %>
- <% groups.each do |group| -%>
- <label>
- <%= check_box_tag "member_of[" + group.id.to_s + "]", value = "1", checked = @student.group_ids.include?(group.id) %>
- <%=group.identifier%>
- </label><br/>
- <% end -%>
-</div>
-
-<div class="group">
- <%= f.label :fname, t(:Fname), :class => :label %>
- <%= f.text_field :fname, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :sname, t(:Sname), :class => :label %>
- <%= f.text_field :sname, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :personal_number, t(:Personal_Num), :class => :label %>
- <%= f.text_field :personal_number, :class => 'text_field' %>
- <span class="description"><%=t :Personal_Num_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :gender, t(:Gender), :class => :label %>
- <%= select "student", "gender", ['male', 'female', 'unknown'].map { |g| [ t(g).titlecase, g ] } %><br/>
- <span class="description"><%=t:Gender_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :main_interest_id, t(:Main_Interest), :class => :label %>
- <%= select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] } %><br/>
-</div>
-
-<div class="group">
- <%= f.label :email, t(:Email), :class => :label %>
- <%= f.text_field :email, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :mailing_lists, t(:Mailing_Lists), :class => :label %>
- <% mailing_lists.each do |ml| -%>
- <% if ml.club == nil || ml.club == @club -%>
- <label><td><%= check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id) %> <%=ml.description%></label><br/>
- <% end -%>
- <% end -%>
- </table>
-</div>
-
-<div class="group">
- <%= f.label :home_phone, t(:Home_phone), :class => :label %>
- <%= f.text_field :home_phone, :class => 'text_field' %>
- <span class="description"><%=t :Phone_number_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :mobile_phone, t(:Mobile_phone), :class => :label %>
- <%= f.text_field :mobile_phone, :class => 'text_field' %>
- <span class="description"><%=t :Phone_number_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :street, t(:Street), :class => :label %>
- <%= f.text_field :street, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :zipcode, t(:Zipcode), :class => :label %>
- <%= f.text_field :zipcode, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :city, t(:City), :class => :label %>
- <%= f.text_field :city, :class => 'text_field' %>
-</div>
-
-<div class="group">
- <%= f.label :title_id, t(:Title), :class => :label %>
- <%= select "student", "title_id", titles.map { |g| [ g.title, g.id ] } %><br/>
-</div>
-
-<div class="group">
- <%= f.label :club_position_id, t(:Club_Position), :class => :label %>
- <%= select "student", "club_position_id", club_positions.map { |g| [ g.position, g.id ] } %><br/>
-</div>
-
-<div class="group">
- <%= f.label :board_position_id, t(:Board_Position), :class => :label %>
- <%= select "student", "board_position_id", board_positions.map { |g| [ g.position, g.id ] } %><br/>
-</div>
-
-<div class="group">
- <%= f.label :comments, t(:Comments), :class => :label %>
- <%= f.text_area :comments, :class => 'text_area', :rows => 4, :cols => 16 %>
-</div>
-
-<div class="group">
- <%= f.label :password, t(:New_Password), :class => :label %>
- <%= f.password_field :password, :class => 'text_field' %>
- <span class="description"><%=t :New_Password_descr%></span>
-</div>
-
-<div class="group">
- <%= f.label :password_confirmation, t(:Confirm_Password), :class => :label %>
- <%= f.password_field :password_confirmation, :class => 'text_field' %>
-</div>
-
-<div class="group navform">
- <input type="submit" class="button" value="<%=t :Save%> →" />
- <% if controller.action_name != "new" && controller.action_name != "create" %>
- <% if current_user.delete_permission?(@club) %>
- <%=t(:or)%> <%= link_to t(:Destroy), @student, :confirm => t(:Are_you_sure_student), :method => :delete %>
- <% end %>
- <%=t :or%> <%= link_to t(:Cancel), student_path(@student) %>
- <% end %>
-</div>
diff --git a/app/views/students/_form.html.haml b/app/views/students/_form.html.haml
new file mode 100644
index 0000000..5746023
--- /dev/null
+++ b/app/views/students/_form.html.haml
@@ -0,0 +1,103 @@
+= f.hidden_field :club_id, :class => 'text_field'
+
+.group
+ %label.label= t(:Groups)
+ - groups.each do |group|
+ = check_box_tag "member_of[" + group.id.to_s + "]", value = "1", checked = @student.group_ids.include?(group.id), :class => 'checkbox'
+ %label{ :for => "member_of_" + group.id.to_s }= group.identifier
+ %br
+
+.group
+ = f.label :fname, t(:Fname), :class => :label
+ = f.text_field :fname, :class => 'text_field'
+
+.group
+ = f.label :sname, t(:Sname), :class => :label
+ = f.text_field :sname, :class => 'text_field'
+
+.group
+ = f.label :personal_number, t(:Personal_Num), :class => :label
+ = f.text_field :personal_number, :class => 'text_field'
+ %span.description= t(:Personal_Num_descr)
+
+.group
+ = f.label :gender, t(:Gender), :class => :label
+ = select "student", "gender", ['male', 'female', 'unknown'].map { |g| [ t(g).titlecase, g ] }
+ %br
+ %span.description= t(:Gender_descr)
+
+.group
+ = f.label :main_interest_id, t(:Main_Interest), :class => :label
+ = select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] }
+ %br
+
+.group
+ = f.label :email, t(:Email), :class => :label
+ = f.text_field :email, :class => 'text_field'
+
+.group
+ %label.label= t(:Mailing_Lists)
+ - mailing_lists.each do |ml|
+ - if ml.club == nil || ml.club == @club
+ = check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id), :class => 'checkbox'
+ %label{ :for => "subscribes_to_" + ml.id.to_s }= ml.description
+ %br
+
+.group
+ = f.label :home_phone, t(:Home_phone), :class => :label
+ = f.text_field :home_phone, :class => 'text_field'
+ %span.description= t(:Phone_number_descr)
+
+.group
+ = f.label :mobile_phone, t(:Mobile_phone), :class => :label
+ = f.text_field :mobile_phone, :class => 'text_field'
+ %span.description= t(:Phone_number_descr)
+
+.group
+ = f.label :street, t(:Street), :class => :label
+ = f.text_field :street, :class => 'text_field'
+
+.group
+ = f.label :zipcode, t(:Zipcode), :class => :label
+ = f.text_field :zipcode, :class => 'text_field'
+
+.group
+ = f.label :city, t(:City), :class => :label
+ = f.text_field :city, :class => 'text_field'
+
+.group
+ = f.label :title_id, t(:Title), :class => :label
+ = select "student", "title_id", titles.map { |g| [ g.title, g.id ] }
+ %br
+
+.group
+ = f.label :club_position_id, t(:Club_Position), :class => :label
+ = select "student", "club_position_id", club_positions.map { |g| [ g.position, g.id ] }
+ %br
+
+.group
+ = f.label :board_position_id, t(:Board_Position), :class => :label
+ = select "student", "board_position_id", board_positions.map { |g| [ g.position, g.id ] }
+ %br
+
+.group
+ = f.label :comments, t(:Comments), :class => :label
+ = f.text_area :comments, :class => 'text_area', :rows => 4, :cols => 16
+
+.group
+ = f.label :password, t(:New_Password), :class => :label
+ = f.password_field :password, :class => 'text_field'
+ %span.description= t(:New_Password_descr)
+
+.group
+ = f.label :password_confirmation, t(:Confirm_Password), :class => :label
+ = f.password_field :password_confirmation, :class => 'text_field'
+
+.group.navform
+ %input.button{ :type => 'submit', :value => t(:Save) + " →" }
+ - if controller.action_name != "new" && controller.action_name != "create"
+ - if current_user.delete_permission?(@club)
+ = t(:or)
+ = link_to t(:Destroy), @student, :confirm => t(:Are_you_sure_student), :method => :delete
+ = t(:or)
+ = link_to t(:Cancel), student_path(@student)
diff --git a/app/views/user_sessions/new.html.haml b/app/views/user_sessions/new.html.haml
index b876fa5..611c5c3 100644
--- a/app/views/user_sessions/new.html.haml
+++ b/app/views/user_sessions/new.html.haml
@@ -1,19 +1,19 @@
.block
.content
%h2.title= t:Log_in
.inner
- form_for @user_session, :url => user_session_path, :html => { :class => 'form' } do |f|
.group
= f.label :login, t(:Login_or_email), :class => 'label'
= f.text_field :login, :class => 'text_field'
.group
= f.label :password, t(:Password), :class => 'label'
= f.password_field :password, :class => 'text_field'
.group
= f.check_box :remember_me, :class => 'check_box'
- = f.label t(:Remember_me)
+ = f.label :remember_me, t(:Remember_me)
.group
= f.submit t(:Log_in)
.group
= link_to t(:Forgot_password), new_password_reset_path
diff --git a/test/unit/grade_test.rb b/test/unit/grade_test.rb
deleted file mode 100644
index e52d1c6..0000000
--- a/test/unit/grade_test.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'test_helper'
-
-class GradeTest < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
|
calmh/Register
|
4cdda39b7588bbd3b611b6190c9b2dba35006b1b
|
Replace fixtures with factory_girl. All tests now need refactoring.
|
diff --git a/config/environment.rb b/config/environment.rb
index 8df79db..695be09 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,96 +1,97 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
REQUIRE_PERSONAL_NUMBER = true
# Setting this to true will allow birthdates instead of full personal numbers.
# Validations will still be performed on personal numbers.
BIRTHDATE_IS_ENOUGH = true
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
+ config.gem "factory_girl"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
diff --git a/test/factories.rb b/test/factories.rb
new file mode 100644
index 0000000..96f335e
--- /dev/null
+++ b/test/factories.rb
@@ -0,0 +1,93 @@
+def cached_association(key)
+ object = key.to_s.camelize.constantize.first
+ object ||= Factory(key)
+end
+
+Factory.sequence :pnumber do |n|
+ personal_number = '19800101-' + '%03d'%n
+
+ # Calculate valid check digit
+ fact = 2
+ sum = 0
+ personal_number.sub("-", "").split(//)[2..13].each do |n|
+ (n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
+ fact = 3 - fact
+ end
+ check = (10 - sum) % 10
+
+ personal_number + check.to_s
+end
+
+Factory.define :grade_category do |c|
+ c.sequence(:category) { |n| "Category #{n}" }
+end
+
+Factory.define :grade do |c|
+ c.sequence(:level) { |n| n }
+ c.description { |g| "Grade #{g.level}" }
+end
+
+Factory.define :graduation do |f|
+ f.instructor "Instructor"
+ f.examiner "Examiner"
+ f.graduated Time.now
+ f.grade { cached_association(:grade) }
+ f.grade_category { cached_association(:grade) }
+ f.student { cached_association(:grade) }
+end
+
+Factory.define :club do |c|
+ c.sequence(:name) {|n| "Club #{n}" }
+end
+
+Factory.define :board_position do |c|
+ c.position "Secretary"
+end
+
+Factory.define :club_position do |c|
+ c.position "Instructor"
+end
+
+Factory.define :title do |c|
+ c.title "Student"
+ c.level 1
+end
+
+Factory.define :payment do |c|
+ c.amount 700
+ c.received Time.now
+ c.description "Comment"
+end
+
+Factory.define :student do |s|
+ s.fname 'John'
+ s.sequence(:sname) {|n| "Doe_#{n}" }
+ s.password "password"
+ s.password_confirmation "password"
+ s.sequence(:email) { |n| "person#{n}@example.com" }
+ s.personal_number { Factory.next(:pnumber) }
+ s.main_interest { cached_association(:grade_category) }
+ s.club { cached_association(:club) }
+ s.club_position { cached_association(:club_position) }
+ s.board_position { cached_association(:board_position) }
+ s.title { cached_association(:title) }
+end
+
+Factory.define :administrator do |s|
+ s.fname 'Admin'
+ s.sequence(:sname) {|n| "Istrator_#{n}" }
+ s.password "password"
+ s.password_confirmation "password"
+ s.sequence(:email) {|n| "admin#{n}@example.com" }
+ s.sequence(:login) {|n| "admin#{n}" }
+ s.clubs_permission false
+ s.users_permission false
+ s.groups_permission false
+ s.mailinglists_permission false
+end
+
+Factory.define :permission do |p|
+ p.association :club
+ p.association :user, :factory => :administrator
+ p.permission "read"
+end
diff --git a/test/fixtures/board_positions.yml b/test/fixtures/board_positions.yml
deleted file mode 100644
index 696709a..0000000
--- a/test/fixtures/board_positions.yml
+++ /dev/null
@@ -1,31 +0,0 @@
----
-board_positions_001:
- position: Ingen
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "1"
-board_positions_002:
- position: Sekreterare
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "219965772"
-board_positions_003:
- position: Suppleant
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "326696169"
-board_positions_004:
- position: "Kass\xC3\xB6r"
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "336935152"
-board_positions_005:
- position: Ledamot
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "612355200"
-board_positions_006:
- position: "Ordf\xC3\xB6rande"
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "974871007"
diff --git a/test/fixtures/club_positions.yml b/test/fixtures/club_positions.yml
deleted file mode 100644
index 86310be..0000000
--- a/test/fixtures/club_positions.yml
+++ /dev/null
@@ -1,21 +0,0 @@
----
-club_positions_002:
- position: "Chefsinstrukt\xC3\xB6r"
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "132021022"
-club_positions_003:
- position: "Instrukt\xC3\xB6r"
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "517417634"
-club_positions_004:
- position: Divisionschef
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "819547023"
-club_positions_001:
- position: Ingen
- created_at: 2009-12-21 09:12:31
- updated_at: 2009-12-21 09:12:31
- id: "1"
diff --git a/test/fixtures/clubs.yml b/test/fixtures/clubs.yml
deleted file mode 100644
index c287db7..0000000
--- a/test/fixtures/clubs.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-clubs_006:
- name: Nybro
- id: "9"
-clubs_001:
- name: "Br\xC3\xA5landa"
- id: "2"
-clubs_002:
- name: "Vall\xC3\xA5kra"
- id: "3"
-clubs_003:
- name: "Frilles\xC3\xA5s"
- id: "4"
-clubs_004:
- name: Tandsbyn
- id: "5"
-clubs_005:
- name: Edsvalla
- id: "8"
diff --git a/test/fixtures/configuration_settings.yml b/test/fixtures/configuration_settings.yml
deleted file mode 100644
index d178bad..0000000
--- a/test/fixtures/configuration_settings.yml
+++ /dev/null
@@ -1,9 +0,0 @@
----
-configuration_settings_001:
- created_at: 2009-12-16 17:44:10
- updated_at: 2009-12-16 17:44:10
- id: "980190963"
- setting: |
- --- :site_name
-
- value: T.I.A. Register
diff --git a/test/fixtures/grade_categories.yml b/test/fixtures/grade_categories.yml
deleted file mode 100644
index ef6dcad..0000000
--- a/test/fixtures/grade_categories.yml
+++ /dev/null
@@ -1,13 +0,0 @@
----
-grade_categories_001:
- category: Kung Fu
- id: "1"
-grade_categories_002:
- category: Sanshou
- id: "2"
-grade_categories_003:
- category: Qi Gong
- id: "3"
-grade_categories_004:
- category: Junior
- id: "4"
diff --git a/test/fixtures/grades.yml b/test/fixtures/grades.yml
deleted file mode 100644
index c095c93..0000000
--- a/test/fixtures/grades.yml
+++ /dev/null
@@ -1,53 +0,0 @@
----
-grades_007:
- level: "7"
- id: "7"
- description: !binary |
- QmzDpSBJ
-
-grades_008:
- level: "8"
- id: "8"
- description: "Bl\xC3\xA5 II"
-grades_009:
- level: "9"
- id: "9"
- description: Svart I
-grades_010:
- level: "10"
- id: "10"
- description: Svart II
-grades_011:
- level: "11"
- id: "11"
- description: Svart III
-grades_012:
- level: "12"
- id: "12"
- description: Svart IIII
-grades_001:
- level: "1"
- id: "1"
- description: !binary |
- UsO2ZCBJ
-
-grades_002:
- level: "2"
- id: "2"
- description: "R\xC3\xB6d II"
-grades_003:
- level: "3"
- id: "3"
- description: Gul I
-grades_004:
- level: "4"
- id: "4"
- description: Gul II
-grades_005:
- level: "5"
- id: "5"
- description: "Gr\xC3\xB6n I"
-grades_006:
- level: "6"
- id: "6"
- description: "Gr\xC3\xB6n II"
diff --git a/test/fixtures/graduations.yml b/test/fixtures/graduations.yml
deleted file mode 100644
index 2e43607..0000000
--- a/test/fixtures/graduations.yml
+++ /dev/null
@@ -1,101 +0,0 @@
----
-graduations_007:
- student_id: "31"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "649039798"
- graduated: 2009-02-28 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_008:
- student_id: "29"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "980190962"
- graduated: 2005-11-26 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_009:
- student_id: "32"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "1067900430"
- graduated: 2007-06-16 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_010:
- student_id: "25"
- instructor: Foo2
- created_at: 2009-12-15 09:41:24
- grade_category_id: "1"
- updated_at: 2009-12-15 09:41:24
- id: "1067900431"
- graduated: 2009-06-27 00:00:00
- grade_id: "1"
- examiner: Annan
-graduations_001:
- student_id: "135"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "12450259"
- graduated: 2001-05-18 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_002:
- student_id: "34"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "144830109"
- graduated: 2009-03-09 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_003:
- student_id: "30"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "265038470"
- graduated: 2006-05-13 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_004:
- student_id: "30"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "298486374"
- graduated: 2009-05-13 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_005:
- student_id: "94"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "322694357"
- graduated: 2008-05-30 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
-graduations_006:
- student_id: "34"
- instructor: Kristoffer Jansson
- created_at: 2009-12-09 09:09:19
- grade_category_id: "1"
- updated_at: 2009-12-09 09:09:19
- id: "404681484"
- graduated: 2007-06-16 12:00:00
- grade_id: "1"
- examiner: Johan Martinsson
diff --git a/test/fixtures/groups.yml b/test/fixtures/groups.yml
deleted file mode 100644
index 1bbeca7..0000000
--- a/test/fixtures/groups.yml
+++ /dev/null
@@ -1,19 +0,0 @@
----
-groups_001:
- created_at: 2009-12-09 09:09:19
- comments:
- updated_at: 2009-12-09 09:09:19
- id: "7"
- identifier: Nyregistrerad
-groups_002:
- created_at: 2009-12-09 09:09:19
- comments:
- updated_at: 2009-12-09 09:09:19
- id: "8"
- identifier: "Instrukt\xC3\xB6rer"
-groups_003:
- created_at: 2009-12-09 09:09:19
- comments:
- updated_at: 2009-12-09 09:09:19
- id: "10"
- identifier: Elever
diff --git a/test/fixtures/groups_students.yml b/test/fixtures/groups_students.yml
deleted file mode 100644
index 73f546e..0000000
--- a/test/fixtures/groups_students.yml
+++ /dev/null
@@ -1,49 +0,0 @@
----
-groups_students_011:
- student_id: "27"
- group_id: "10"
-groups_students_012:
- student_id: "26"
- group_id: "8"
-groups_students_001:
- student_id: "30"
- group_id: "7"
-groups_students_013:
- student_id: "26"
- group_id: "10"
-groups_students_002:
- student_id: "29"
- group_id: "10"
-groups_students_014:
- student_id: "136"
- group_id: "10"
-groups_students_003:
- student_id: "36"
- group_id: "10"
-groups_students_015:
- student_id: "34"
- group_id: "10"
-groups_students_004:
- student_id: "32"
- group_id: "10"
-groups_students_016:
- student_id: "614887029"
- group_id: "7"
-groups_students_005:
- student_id: "25"
- group_id: "10"
-groups_students_006:
- student_id: "137"
- group_id: "7"
-groups_students_007:
- student_id: "31"
- group_id: "8"
-groups_students_008:
- student_id: "31"
- group_id: "10"
-groups_students_009:
- student_id: "135"
- group_id: "7"
-groups_students_010:
- student_id: "35"
- group_id: "10"
diff --git a/test/fixtures/mailing_lists.yml b/test/fixtures/mailing_lists.yml
deleted file mode 100644
index 5d34a23..0000000
--- a/test/fixtures/mailing_lists.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-mailing_lists_001:
- security: private
- description: Instructors
- email: [email protected]
- default: 0
- id: 1
-mailing_lists_002:
- security: public
- description: Everyone
- email: [email protected]
- default: 0
- id: 2
-mailing_lists_003:
- security: public
- description: Brålanda-elever
- email: [email protected]
- id: 3
- club_id: 2
- default: 1
diff --git a/test/fixtures/mailing_lists_students.yml b/test/fixtures/mailing_lists_students.yml
deleted file mode 100644
index 9ae0812..0000000
--- a/test/fixtures/mailing_lists_students.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-mailing_lists_students_001:
- student_id: 25
- mailing_list_id: 1
diff --git a/test/fixtures/payments.yml b/test/fixtures/payments.yml
deleted file mode 100644
index db3c063..0000000
--- a/test/fixtures/payments.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-payments_001:
- student_id: "30"
- amount: "100.0"
- id: "225070851"
- received: <%= 14.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift VT2009"
-payments_002:
- student_id: "30"
- amount: "500.0"
- id: "319740578"
- received: <%= 14.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift VT2009"
-payments_003:
- student_id: "29"
- amount: "100.0"
- id: "980190962"
- received: <%= 14.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift VT2009"
-payments_004:
- student_id: "31"
- amount: "50.0"
- id: "980254618"
- received: <%= 14.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift HT2009"
-payments_005:
- student_id: "135"
- amount: "2.0"
- id: "1005520445"
- received: <%= 4.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift HT2009"
-payments_006:
- student_id: "94"
- amount: "700.0"
- id: "1025039570"
- received: <%= 4.months.ago.to_s(:db) %>
- description: "Tr\xC3\xA4ningsavgift HT2009"
diff --git a/test/fixtures/permissions.yml b/test/fixtures/permissions.yml
deleted file mode 100644
index f0fd4b3..0000000
--- a/test/fixtures/permissions.yml
+++ /dev/null
@@ -1,140 +0,0 @@
-permissions_030:
- club_id: "8"
- user_id: "30"
- permission: payments
-permissions_019:
- club_id: "3"
- user_id: "1"
- permission: graduations
-permissions_008:
- club_id: "9"
- user_id: "1"
- permission: edit
-permissions_031:
- club_id: "8"
- user_id: "30"
- permission: read
-permissions_020:
- club_id: "4"
- user_id: "1"
- permission: edit
-permissions_009:
- club_id: "9"
- user_id: "1"
- permission: delete
-permissions_032:
- club_id: "8"
- user_id: "1"
- permission: delete
-permissions_021:
- club_id: "4"
- user_id: "1"
- permission: delete
-permissions_010:
- club_id: "9"
- user_id: "1"
- permission: payments
-permissions_033:
- club_id: "8"
- user_id: "1"
- permission: payments
-permissions_022:
- club_id: "4"
- user_id: "1"
- permission: payments
-permissions_011:
- club_id: "9"
- user_id: "1"
- permission: graduations
-permissions_034:
- club_id: "8"
- user_id: "1"
- permission: graduations
-permissions_023:
- club_id: "4"
- user_id: "1"
- permission: graduations
-permissions_012:
- club_id: "2"
- user_id: "1"
- permission: edit
-permissions_001:
- club_id: "8"
- user_id: "1"
- permission: read
-permissions_024:
- club_id: "5"
- user_id: "1"
- permission: edit
-permissions_013:
- club_id: "2"
- user_id: "1"
- permission: delete
-permissions_002:
- club_id: "9"
- user_id: "1"
- permission: read
-permissions_025:
- club_id: "5"
- user_id: "1"
- permission: delete
-permissions_014:
- club_id: "2"
- user_id: "1"
- permission: payments
-permissions_003:
- club_id: "2"
- user_id: "1"
- permission: read
-permissions_026:
- club_id: "5"
- user_id: "1"
- permission: payments
-permissions_015:
- club_id: "2"
- user_id: "1"
- permission: graduations
-permissions_004:
- club_id: "3"
- user_id: "1"
- permission: read
-permissions_027:
- club_id: "5"
- user_id: "1"
- permission: graduations
-permissions_016:
- club_id: "3"
- user_id: "1"
- permission: edit
-permissions_005:
- club_id: "4"
- user_id: "1"
- permission: read
-permissions_028:
- club_id: "8"
- user_id: "30"
- permission: edit
-permissions_017:
- club_id: "3"
- user_id: "1"
- permission: delete
-permissions_006:
- club_id: "5"
- user_id: "1"
- permission: read
-permissions_029:
- club_id: "8"
- user_id: "30"
- permission: delete
-permissions_018:
- club_id: "3"
- user_id: "1"
- permission: payments
-permissions_007:
- club_id: "8"
- user_id: "1"
- permission: edit
-permissions_100:
- club_id: "8"
- user_id: "1"
- permission: export
diff --git a/test/fixtures/titles.yml b/test/fixtures/titles.yml
deleted file mode 100644
index 978450d..0000000
--- a/test/fixtures/titles.yml
+++ /dev/null
@@ -1,25 +0,0 @@
----
-titles_001:
- created_at: 2009-12-21 09:12:31
- title: Toe tai
- updated_at: 2009-12-21 09:12:31
- level: "1"
- id: "1"
-titles_002:
- created_at: 2009-12-21 09:12:31
- title: Djo gau
- updated_at: 2009-12-21 09:12:31
- level: "2"
- id: "2"
-titles_003:
- created_at: 2009-12-21 09:12:31
- title: Gau lin
- updated_at: 2009-12-21 09:12:31
- level: "3"
- id: "3"
-titles_004:
- created_at: 2009-12-21 09:12:31
- title: Sifu
- updated_at: 2009-12-21 09:12:31
- level: "4"
- id: "4"
diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml
deleted file mode 100644
index 2ec1ab6..0000000
--- a/test/fixtures/users.yml
+++ /dev/null
@@ -1,570 +0,0 @@
-users_015:
- city: "Vall\xC3\xA5kra"
- single_access_token: zDafGGhEtEtfK9g11eZx
- last_request_at:
- personal_number: 19850107-1768
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: OS2yY7jSgwHnI0HmUvBv
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "26030"
- main_interest_id: "1"
- groups_permission:
- club_id: "3"
- board_position_id: "1"
- id: "614887029"
- current_login_ip:
- street: "Mj\xC3\xB6lkal\xC3\xA5nga 64"
- home_phone: 042-3409841
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 181ce34df4e5704fb47f07dd41209df8840903c9e2e0d1595b0e1b37086d4771d19678af672a68b442f5d1ea85c4492618e346c09ea2566dc25d2864494b2669
- users_permission:
- mailinglists_permission:
- fname: Marielle
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Dahlberg
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_004:
- city: Arvidsjaur
- single_access_token: pLUnSxRXdioKC6DrVs48
- last_request_at:
- personal_number: 19710730-3187
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: qLIqIc9Eulplp2gVOV2Q
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "93000"
- main_interest_id: "2"
- groups_permission:
- club_id: "2"
- board_position_id: "1"
- id: "27"
- current_login_ip:
- street: Barrgatan 81
- home_phone: 0960-8472971
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 26db96d89f9b07cb86e3980ddbcf3382b668e8537ef9ab90f6a9a5430840ce406ea4c161a6f43fe7e4142e9944f63586242896367e10b3ea4079386571f5852d
- users_permission:
- mailinglists_permission:
- fname: Emma
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Petterson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_005:
- city: "Svart\xC3\xA5"
- single_access_token: WLpBRwcuouV2JocfhNXd
- last_request_at:
- personal_number: 19420814-3778
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: fIDpa7BWiLZXoPeJxFdT
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "69330"
- main_interest_id: "1"
- groups_permission:
- club_id: "3"
- board_position_id: "1"
- id: "29"
- current_login_ip:
- street: "Verdandi Gr\xC3\xA4nd 65"
- home_phone: ""
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 85f36153d06ac5c77e31f88655341bcad50ea360a1680d5b883f5ddecb9e64c6c1da1258f4b0c631df11900956698d49848ec6de0398714ef1eabaa0bca98217
- users_permission:
- mailinglists_permission:
- fname: Emil
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: "Nystr\xC3\xB6m"
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_006:
- city:
- single_access_token: PukZmC0UFMPgAS6XOieY
- last_request_at:
- personal_number:
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments:
- crypted_password: 9bad0e92a8e4e713700495c3e058cd1c0781396b3ef7ae3a6d06eceaca5f634b
- perishable_token: OiANbF63ZoKpxPUuZGbs
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode:
- main_interest_id:
- groups_permission: "0"
- club_id:
- board_position_id:
- id: "30"
- current_login_ip:
- street:
- home_phone:
- gender:
- failed_login_count:
- type: Administrator
- title_id:
- current_login_at:
- login_count:
- persistence_token: e12a68f9f736ea810817e7b5822130e187a239a78715820ec21003489f748c83965bb48e0fef5eefb2f7de6cb4faa380487c808442d6cb05d8cb2a6721257086
- users_permission: "0"
- mailinglists_permission: "0"
- fname: Chief
- last_login_ip:
- site_permission: "0"
- last_login_at:
- login: ci
- sname: Instructor
- clubs_permission: "0"
- email: [email protected]
- club_position_id:
- mobile_phone:
-users_007:
- city: Kristianstad
- single_access_token: G2-Mx5dZZv1Sztom3ESU
- last_request_at:
- personal_number: 19460723-4780
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: kIAInJyDT5aTVEy8J5pc
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "12353"
- main_interest_id: "3"
- groups_permission:
- club_id: "4"
- board_position_id: "1"
- id: "31"
- current_login_ip:
- street: "Norra B\xC3\xA4ckebo 5"
- home_phone: 044-212936
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 87527942b789db8c88d2a9f81c263e951d7134a01419cb5f67904b679d65200c38009fcbac11e239472d45fdbff3c94d89c30fb2e64650948042dc2d875a307c
- users_permission:
- mailinglists_permission:
- fname: Elif
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Johnsson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_008:
- city: "Frilles\xC3\xA5s"
- single_access_token: AbZ6siLotedB55t3a0N6
- last_request_at:
- personal_number: 19810628-1861
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: V4O3hMrdtyH6Raegbp1K
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "43030"
- main_interest_id: "1"
- groups_permission:
- club_id: "4"
- board_position_id: "1"
- id: "32"
- current_login_ip:
- street: "Tuvv\xC3\xA4gen 20"
- home_phone: ""
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 1b9fc09c5f843dc0d05ad9f767aab9e53e05af07954cd0538896cc70aa417ff49f91251a84fb254667e521aebf1cb97d52843ee8c22265a0c401d665b9dfc9b1
- users_permission:
- mailinglists_permission:
- fname: Lisen
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Berggren
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_010:
- city: Tandsbyn
- single_access_token: 4f0mzVSsGtutT4lR788A
- last_request_at:
- personal_number: 19671029-1219
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: 2tzua9jnq8Ieyg1C7YIW
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "83021"
- main_interest_id: "2"
- groups_permission:
- club_id: "5"
- board_position_id: "1"
- id: "35"
- current_login_ip:
- street: Stallstigen 47
- home_phone: 063-5312134
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: c8dd0a057199cb3386c2da4ab9fa84cbdcd3a70058685626d06ee551a000990e6c1e5d65b1bffa50a384046787d706594ff1cee76153025569e71c3b097a5f17
- users_permission:
- mailinglists_permission:
- fname: Nino
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Berg
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_009:
- city: Kvicksund
- single_access_token: QBIZWu_swyIvbvjgzAcn
- last_request_at:
- personal_number: 19581214-1496
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: Hl0KIzquCA5fmMoHMs6n
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "64045"
- main_interest_id: "1"
- groups_permission:
- club_id: "4"
- board_position_id: "1"
- id: "34"
- current_login_ip:
- street: "Kl\xC3\xA4ppinge 89"
- home_phone: 0563-9198417
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: ad3ce523fcc6b40f2593c5c8b980aec9e530a749d1895f51a5368070dda1991f0078ae045ca369fa12f16d544edfcedd4e5c3252a3855a264b9eccef800b3f7f
- users_permission:
- mailinglists_permission:
- fname: Edgar
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Holmberg
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_011:
- city: "F\xC3\xA5gelfors"
- single_access_token: LGOQfxGdt4YOrU5asK6O
- last_request_at:
- personal_number: 19670425-7176
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: 8-LO-mmC6NRCr-M8tLvF
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "57075"
- main_interest_id: "1"
- groups_permission:
- club_id: "5"
- board_position_id: "1"
- id: "36"
- current_login_ip:
- street: ""
- home_phone: 0491-5675992
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 629d78c925e23604c16d10df964fad2e83b433b69125f9feff45f6bb3254361d6c713aba6b5e8f9d638e2422e327ecb953e5ed4a8e69f8a3ae9de39ce71043f0
- users_permission:
- mailinglists_permission:
- fname: Devin
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Johansson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_012:
- city: Ljungby
- single_access_token: r3-xfoMODusX9u53yZkX
- last_request_at:
- personal_number: 19510709-8054
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: 4fYpUiPrU70vlo86swvz
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "34147"
- main_interest_id: "1"
- groups_permission:
- club_id: "8"
- board_position_id: "1"
- id: "135"
- current_login_ip:
- street: Bygget 73
- home_phone: 0372-9283685
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: cfba9b4d6ed63659b98a6326f749809ad648d59d515f98977ffe4bc0e3dca4337bfebf2069c2b89db5ac731c909ce4da1ea53fcd5e5d59782928c8f990f5f394
- users_permission:
- mailinglists_permission:
- fname: Razmus
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Hermansson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_001:
- city:
- single_access_token: RcNDgaUdOCKapN7hWLUU
- last_request_at: 2010-01-26 18:20:16
- personal_number:
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments:
- crypted_password: 6694a5cda8fcb5ddcfd6171ce35de9e593c20da32b0341917f4f1f6d40ce6d98
- perishable_token: CLSbAu-0HlViX9BHA15J
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode:
- main_interest_id:
- groups_permission: "1"
- club_id:
- board_position_id:
- id: "1"
- current_login_ip: 127.0.0.1
- street:
- home_phone:
- gender:
- failed_login_count: "0"
- type: Administrator
- title_id:
- current_login_at: 2010-01-26 18:20:07
- login_count: "16"
- persistence_token: 0f1dae1907c73885dcbeab9af3105ddf202a6aa8e2dc3ea93b2178a734e183b946a3c5ecfc4bbd7634344dbf7aec7070a4f5976a848ea38ec9d64a31d27c489a
- users_permission: "1"
- mailinglists_permission: "1"
- fname: Admin
- last_login_ip: 127.0.0.1
- site_permission: "1"
- last_login_at: 2010-01-26 18:15:07
- login: admin
- sname: Istrator
- clubs_permission: "1"
- email: [email protected]
- club_position_id:
- mobile_phone:
-users_013:
- city: Edsvalla
- single_access_token: LaRu89LjhsoSjbl5oUW2
- last_request_at:
- personal_number: 19500513-8515
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: xHgKK1uasoMGO2Dt_E1C
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "66052"
- main_interest_id: "1"
- groups_permission:
- club_id: "8"
- board_position_id: "1"
- id: "136"
- current_login_ip:
- street: ""
- home_phone: 054-7334012
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 301e09c1198d69f3d609a517d58ac3c1a0f84d15c698627acaba710292eb7c574bae66d99a0cb12f236e4bdf3b8ff998c119d9d2e24a821729a8f074e8d26f73
- users_permission:
- mailinglists_permission:
- fname: Baran
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Olofsson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_002:
- city: "Br\xC3\xA5landa"
- single_access_token: 1Is4aPKS401krBlSDD7Z
- last_request_at:
- personal_number: 19810203-9909
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: r-Wjwf1Dbtqe5oSEQKt-
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "46065"
- main_interest_id: "3"
- groups_permission:
- club_id: "2"
- board_position_id: "1"
- id: "25"
- current_login_ip:
- street: Valldammsgatan 42
- home_phone: 0521-9520867
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: f464267a0b07fda46e6ebc1e42e5a7f4ddba7992c230a814ca2d3f5cae79541f0da9f61c21195a94c195e38f3eccf7bd056263999047e3a04566040308d259c3
- users_permission:
- mailinglists_permission:
- fname: Amalia
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Gustavsson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_014:
- city: Nybro
- single_access_token: mFlg5QnvGvSij7hU7TpA
- last_request_at:
- personal_number: 19450326-9377
- created_at: <%= 14.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: Bc-8EaOIqSYd1d4TJ1mH
- updated_at: <%= 14.months.ago.to_s(:db) %>
- zipcode: "0"
- main_interest_id: "1"
- groups_permission:
- club_id: "9"
- board_position_id: "1"
- id: "137"
- current_login_ip:
- street: Valldammsgatan 42
- home_phone: 0481-5635981
- gender: male
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: bd184489c816e9713f0e7a80b877e1566c2069b92ecce03cce7ca08c6418c80ee1921eb3bcec1e49da2440a55f9cd919d8d0f7b13482bb7e1aa734c7014b1f93
- users_permission:
- mailinglists_permission:
- fname: Svante
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Jansson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
-users_003:
- city: "F\xC3\x96LLINGE"
- single_access_token: wZH5gvpBWujlA_Vmvhka
- last_request_at:
- personal_number: 19620629-3349
- created_at: <%= 1.months.ago.to_s(:db) %>
- comments: ""
- crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
- perishable_token: rpa8hlTBpAhcuftX8lC6
- updated_at: <%= 1.months.ago.to_s(:db) %>
- zipcode: "83066"
- main_interest_id: "1"
- groups_permission:
- club_id: "2"
- board_position_id: "1"
- id: "26"
- current_login_ip:
- street: "Norrfj\xC3\xA4ll 44"
- home_phone: 0645-7595472
- gender: female
- failed_login_count:
- type: Student
- title_id: "1"
- current_login_at:
- login_count:
- persistence_token: 508d9227ac884460493a5a07a66af16dd5a363fa116bf421a824c1f9f911e92090bb212728fa05d5c26bf4fb6a207261ec11a86256093f2888ead23d78165f46
- users_permission:
- mailinglists_permission:
- fname: Agaton
- last_login_ip:
- site_permission:
- last_login_at:
- login:
- sname: Johnsson
- clubs_permission:
- email: [email protected]
- club_position_id: "1"
- mobile_phone: ""
|
calmh/Register
|
58c1760795336448c6c660104215a9d8ccdd6b4c
|
Clean up personal_number/birthdate testing.
|
diff --git a/app/models/student.rb b/app/models/student.rb
index 1234b6e..2ee40d6 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,127 +1,146 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
- validates_presence_of :personal_number, :if => REQUIRE_PERSONAL_NUMBER
- validates_uniqueness_of :personal_number, :if => Proc.new { |s| !s.personal_number.blank? && s.personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/ }
- validate :check_personal_number
+ validates_presence_of :personal_number, :if => lambda { REQUIRE_PERSONAL_NUMBER }
+ validates_uniqueness_of :personal_number, :if => :personal_number_complete?
+ validate :validate_personal_number,
+ :if => lambda { |s| (REQUIRE_PERSONAL_NUMBER && !BIRTHDATE_IS_ENOUGH) || s.personal_number_complete? }
+ validate :validate_possible_birthdate, :if => lambda { |s| BIRTHDATE_IS_ENOUGH || !s.personal_number.blank? }
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
named_scope :all_inclusive, lambda { |c| {
:conditions => c, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
} }
acts_as_authentic do |c|
c.validate_password_field = true
c.require_password_confirmation = true
c.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..-1].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
sum % 10
end
- def check_personal_number
- if !personal_number.blank?
- errors.add(:personal_number, :invalid) if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d(-\d\d\d\d)?$/
- if personal_number.length == 13:
- errors.add(:personal_number, :incorrect_check_digit) if luhn != 0
+ def personal_number_valid_format?
+ personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/
+ end
+
+ def personal_number_complete?
+ !personal_number.blank? && personal_number_valid_format?
+ end
+
+ def validate_personal_number
+ if personal_number_valid_format?
+ if luhn != 0
+ errors.add(:personal_number, :incorrect_check_digit)
end
+ else
+ errors.add(:personal_number, :invalid)
+ end
+ end
+
+ def validate_possible_birthdate
+ return if personal_number.blank?
+ return if personal_number_valid_format?
+ if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d$/
+ errors.add(:personal_number, :invalid)
end
end
def personal_number=(value)
value = $1 + "-" + $2 if value =~ /^(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(19\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(20\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
p = Payment.new
p.amount = 0
p.received = created_at
p.description = "Start"
return p
end
end
def current_grade
if graduations.blank?
return nil
else
in_main_interest = graduations.select { |g| g.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return graduations[0]
end
end
end
def active?
if payments.blank?
return Time.now - created_at < 86400 * 45
else
return Time.now - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] unless self[:gender].blank?
return 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
d = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today-d) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |g| g.identifier }.join(", ")
end
end
diff --git a/config/environment.rb b/config/environment.rb
index ccf043f..8df79db 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,94 +1,96 @@
# 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.3.5' unless defined? RAILS_GEM_VERSION
COPYRIGHT = "Copyright © 2009-2010 Jakob Borg"
# Setting this to false will disable validates_presence_of on personal_number.
# All other validations will still run when personal_number is present.
# This is useful as a temporary measure when importing data, to clean up later.
-# Tests fails when this is set to false.
-REQUIRE_PERSONAL_NUMBER = Proc.new { true }
+REQUIRE_PERSONAL_NUMBER = true
+# Setting this to true will allow birthdates instead of full personal numbers.
+# Validations will still be performed on personal numbers.
+BIRTHDATE_IS_ENOUGH = true
# 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 "authlogic", :version => "2.1.3"
config.gem "fastercsv"
# 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 = :sv
# 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 => '_Register2_session',
:secret => '1f15d78a3256d02741887694f8ac25bafc5e900a6df8f1265c005aa9ee1551b06e86aa697f22935ec0a656a47d3dec8ed5fd7fe5b136953773cf814752756390'
}
# 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
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<label/
%|<div class="fieldWithErrors">#{html_tag} <span class="error">#{[instance.error_message].join(', ')}</span></div>|
else
html_tag
end
end
diff --git a/test/unit/student_test.rb b/test/unit/student_test.rb
index 2ffe6d1..6038f75 100644
--- a/test/unit/student_test.rb
+++ b/test/unit/student_test.rb
@@ -1,65 +1,127 @@
require 'test_helper'
class StudentTest < ActiveSupport::TestCase
- test "luhn calculation" do
- s = Student.new
- s.personal_number = "198002020710"
- assert s.luhn == 0
- s.personal_number = "197501230580"
- assert s.luhn == 0
- end
-
- test "validations" do
- s = Student.new
- s.sname = "Johansson"
- s.fname = "Karon"
- s.email = "[email protected]"
- s.home_phone = "0410-6495551"
- s.mobile_phone = ""
- s.street = "Bonaröd 78"
- s.zipcode = "23021"
- s.city = "Beddingestrand"
- s.title_id = 1
- s.club_position_id = 1
- s.board_position_id = 1
- s.comments = "None"
- s.main_interest_id = 1
- s.club_id = 9
- s.password = "password"
- s.password_confirmation = "password"
-
- s.personal_number = nil
- assert !s.save # Nil personal number
- s.personal_number = "19710730-3187"
- assert !s.save # Duplicate personal number
- s.personal_number = "abc123"
- assert !s.save # Nonsense personal number
- s.personal_number = ""
- assert !s.save # Blank personal number
- s.personal_number = "20710730-3187"
- assert !s.save # Invalid personal number
- s.personal_number = "710730-3187"
- assert !s.save # Invalid personal number format
- s.personal_number = "7107303187"
- assert !s.save # Invalid personal number format
- s.personal_number = "197107303187"
- assert !s.save # Invalid personal number format
- s.personal_number = "19550213-2490"
- assert s.save # Valid personal number
- s.personal_number = "19710730"
- assert s.save # Valid birth date
-
- s.personal_number = "abc123"
- assert s.personal_number == "abc123"
- s.personal_number = "20710730-3187"
- assert s.personal_number == "20710730-3187"
- s.personal_number = "7107303187"
- assert s.personal_number == "19710730-3187"
- s.personal_number = "710730-3187"
- assert s.personal_number == "19710730-3187"
- s.personal_number = "197107303187"
- assert s.personal_number == "19710730-3187"
- s.personal_number = "19710730-3187"
- assert s.personal_number == "19710730-3187"
- end
+ def setup
+ @student = Student.new
+ @student.sname = "Johansson"
+ @student.fname = "Karon"
+ @student.email = "[email protected]"
+ @student.home_phone = "0410-6495551"
+ @student.mobile_phone = ""
+ @student.street = "Bonaröd 78"
+ @student.zipcode = "23021"
+ @student.city = "Beddingestrand"
+ @student.title_id = 1
+ @student.club_position_id = 1
+ @student.board_position_id = 1
+ @student.comments = "None"
+ @student.main_interest_id = 1
+ @student.club_id = 9
+ @student.password = "password"
+ @student.password_confirmation = "password"
+ @student.personal_number = "19710730"
+ end
+
+ test "luhn calculation valid" do
+ @student.personal_number = "198002020710"
+ assert @student.luhn == 0
+ end
+
+ test "luhn calculation invalid" do
+ @student.personal_number = "198102020710"
+ assert @student.luhn != 0
+ end
+
+ test "personal number must be unique" do
+ @student.personal_number = "19710730-3187"
+ assert [email protected]?
+ end
+
+ test "autocorrection should do nothing with clearly invalid format" do
+ @student.personal_number = "abc123"
+ assert @student.personal_number == "abc123"
+ end
+
+ test "autocorrection should pass on correct format but unreasonable date" do
+ @student.personal_number = "20710730-3187"
+ assert @student.personal_number == "20710730-3187"
+ end
+
+ test "autocorrection should add century and dash" do
+ @student.personal_number = "7107303187"
+ assert @student.personal_number == "19710730-3187"
+ end
+
+ test "autocorrection should add century" do
+ @student.personal_number = "710730-3187"
+ assert @student.personal_number == "19710730-3187"
+ end
+
+ test "autocorrectionion should add dash" do
+ @student.personal_number = "197107303187"
+ assert @student.personal_number == "19710730-3187"
+ end
+
+ test "autocorrect should pass correct personal number" do
+ @student.personal_number = "19710730-3187"
+ assert @student.personal_number == "19710730-3187"
+ end
+
+ test "personal number must follow correct format" do
+ @student.personal_number = "abc123"
+ assert [email protected]?
+ end
+
+ test "personal number must not be too far in the future" do
+ @student.personal_number = "20550213-2490"
+ assert [email protected]?
+ end
+
+ if REQUIRE_PERSONAL_NUMBER
+
+ test "personal number cannot be nil" do
+ @student.personal_number = nil
+ assert [email protected]?
+ end
+
+ test "personal number must not be blank" do
+ @student.personal_number = ""
+ assert [email protected]?
+ end
+
+ test "century digits will be auto added" do
+ @student.personal_number = "550213-2490"
+ assert @student.personal_number == "19550213-2490"
+ assert @student.valid?
+ end
+
+ test "century digits and dash will be auto added" do
+ @student.personal_number = "5502132490"
+ assert @student.personal_number == "19550213-2490"
+ assert @student.valid?
+ end
+
+ test "dash will be auto added" do
+ @student.personal_number = "195502132490"
+ assert @student.personal_number == "19550213-2490"
+ assert @student.valid?
+ end
+
+ test "valid personal number should be accepted" do
+ @student.personal_number = "19550213-2490"
+ assert @student.valid?
+ end
+
+ if BIRTHDATE_IS_ENOUGH
+ test "valid birth date should be accepted" do
+ @student.personal_number = "19550213"
+ assert @student.valid?
+ end
+ else
+ test "only birth date should not be accepted" do
+ @student.personal_number = "19550213"
+ assert [email protected]?
+ end
+ end
+ end
end
|
calmh/Register
|
566f662e9036ff327d6e01d71cc7dcc14efc47ed
|
Implementation of message sending.
|
diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb
new file mode 100644
index 0000000..79ad642
--- /dev/null
+++ b/app/controllers/messages_controller.rb
@@ -0,0 +1,30 @@
+class MessagesController < ApplicationController
+ def new
+ @message = Message.new
+ @message.from = current_user.email
+ @message.subject = get_default(:message_subject)
+ @message.body = get_default(:message_body)
+ @students = Student.find(session[:selected_students]);
+ end
+
+ def update
+ @message = Message.new
+ @message.from = current_user.email
+ @message.body = params[:message][:body]
+ @message.subject = params[:message][:subject]
+ @students = Student.find(session[:selected_students]);
+ @sent = []
+ @noemail = []
+ @students.each do |s|
+ if s.email.blank?
+ @noemail << s
+ else
+ @sent << s if s.deliver_generic_message!(@message)
+ end
+ end
+ session[:selected_students] = nil
+
+ set_default(:message_subject, @message.subject)
+ set_default(:message_body, @message.body)
+ end
+end
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 2aa8751..7db2e0c 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,251 +1,254 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize
@club_id = Club.all.map { |c| c.id }
@sort_field = 'fname'
@sort_order = 'up'
end
def conditions
variables = []
conditions = []
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
variables << @club_id
elsif !@club_id.nil?
conditions << "club_id = ?"
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort do |a, b|
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
end
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv do
if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
return
end
end
end
end
def load_searchparams
@searchparams = SearchParams.new
@searchparams.group_id = params[:gi].to_i unless params[:gi].blank?
@searchparams.grade = params[:gr].to_i unless params[:gr].blank?
@searchparams.title_id = params[:ti].to_i unless params[:ti].blank?
@searchparams.board_position_id = params[:bp].to_i unless params[:bp].blank?
@searchparams.club_position_id = params[:cp].to_i unless params[:cp].blank?
@searchparams.only_active = params[:a].to_i unless params[:a].blank?
@searchparams.sort_field = params[:c] unless params[:c].blank?
@searchparams.sort_order = params[:d] unless params[:d].blank?
if params.key? :ci
@searchparams.club_id = params[:ci].map{|x| x.to_i}
end
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
+ if operation == "bulk_message"
+ redirect_to :controller => 'messages', :action => 'new'
+ end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/helpers/messages_helper.rb b/app/helpers/messages_helper.rb
new file mode 100644
index 0000000..f1bca9f
--- /dev/null
+++ b/app/helpers/messages_helper.rb
@@ -0,0 +1,2 @@
+module MessagesHelper
+end
diff --git a/app/models/message.rb b/app/models/message.rb
new file mode 100644
index 0000000..f6d259a
--- /dev/null
+++ b/app/models/message.rb
@@ -0,0 +1,5 @@
+class Message
+ attr_accessor :from
+ attr_accessor :body
+ attr_accessor :subject
+end
diff --git a/app/models/notifier.rb b/app/models/notifier.rb
index dda2582..4072869 100644
--- a/app/models/notifier.rb
+++ b/app/models/notifier.rb
@@ -1,11 +1,19 @@
class Notifier < ActionMailer::Base
default_url_options[:host] = "www.fiveforms.org"
def password_reset_instructions(user)
subject "Password Reset Instructions"
from "[email protected]"
recipients user.email
sent_on Time.now
body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
end
+
+ def generic_message(user, message)
+ subject message.subject
+ from message.from
+ recipients user.email
+ sent_on Time.now
+ body message.body
+ end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index ea8e5b6..7049b68 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,20 +1,24 @@
class User < ActiveRecord::Base
acts_as_authentic do |c|
Authlogic::CryptoProviders::Sha1.stretches = 1
c.transition_from_crypto_providers = Authlogic::CryptoProviders::Sha1
c.crypto_provider = Authlogic::CryptoProviders::Sha256
c.validate_login_field = false
c.validate_email_field = false
c.validate_password_field = false
c.require_password_confirmation = false
end
def self.find_by_login_or_email(login)
User.find_by_login(login) || User.find_by_email(login)
end
def deliver_password_reset_instructions!
reset_perishable_token!
Notifier.deliver_password_reset_instructions(self)
end
+
+ def deliver_generic_message!(message)
+ Notifier.deliver_generic_message(self, message)
+ end
end
diff --git a/app/views/messages/new.html.haml b/app/views/messages/new.html.haml
new file mode 100644
index 0000000..ed64c40
--- /dev/null
+++ b/app/views/messages/new.html.haml
@@ -0,0 +1,19 @@
+.block
+ .content
+ %h2= t(:Send_Message)
+ .inner
+ %p
+ = t(:for).titlecase
+ = (@students.map { |s| s.name }).join(", ")
+ - form_for @message, :html => { :class => 'form' } do |f|
+ .group
+ = f.label :from, t(:From), :class => 'label'
+ = f.text_field :from, :disabled => true, :class => 'text_field'
+ .group
+ = f.label :subject, t(:Subject), :class => 'label'
+ = f.text_field :subject, :class => 'text_field'
+ .group
+ = f.label :body, t(:Body_text), :class => 'label'
+ = f.text_area :body, :rows => 10, :cols => 40, :class => 'text_area'
+ .group.navform
+ %input.button{ :type => "submit", :value => t(:Send) + " →" }
diff --git a/app/views/messages/update.html.haml b/app/views/messages/update.html.haml
new file mode 100644
index 0000000..1a73bcb
--- /dev/null
+++ b/app/views/messages/update.html.haml
@@ -0,0 +1,14 @@
+.block
+ .content
+ %h2= t(:Send_Message)
+ .inner
+ - if [email protected]?
+ %p
+ = t(:Message_sent_to)
+ = (@sent.map { |s| s.name }).join(", ") + "."
+ - if [email protected]?
+ %p
+ = t(:Couldnt_send_to)
+ = (@noemail.map { |s| s.name }).join(", ")
+ = t(:because_no_email)
+ %p= link_to t(:Back), session[:before_bulk]
diff --git a/app/views/notifier/generic.erb b/app/views/notifier/generic.erb
new file mode 100644
index 0000000..2f21cf8
--- /dev/null
+++ b/app/views/notifier/generic.erb
@@ -0,0 +1 @@
+<%= @body %>
\ No newline at end of file
diff --git a/app/views/students/_list.html.haml b/app/views/students/_list.html.haml
index 5b8ef1a..b81c7dc 100644
--- a/app/views/students/_list.html.haml
+++ b/app/views/students/_list.html.haml
@@ -1,31 +1,32 @@
- form_tag :controller => 'students', :action => 'bulk_operations', :class => "form", :method => "post" do
%table.table.lesspadding
%tr
%th.first
%th= sort_link t(:Name), :fname
- if @displayClubField
%th= sort_link t(:Club), :club
%th= sort_link t(:Main_Interest), :main_interest
%th= t(:Groups)
%th= sort_link t(:Personal_Num), :personal_number
- if @displayPaymentField
%th= sort_link t(:Grade), :current_grade
%th.last= sort_link t(:Latest_Payment), :latest_payment
- else
%th.last= sort_link t(:Grade), :current_grade
- @students.each do |student|
%tr{ :class => cycle("odd", "even") }
%td= check_box_tag "selected_students[]", student.id, false, { :id => 'selected_students_' + student.id.to_s }
%td= link_to student.name, student_path(student)
- if @displayClubField
%td= link_to student.club.name, club_path(student.club)
%td= student.main_interest.category
%td= student.groups.map{ |g| g.identifier }.join(", ")
%td= student.personal_number
%td= grade_str(student.current_grade)
- if @displayPaymentField
%td{ :class => "student-" + (student.active? ? 'active' : 'inactive')}=h student.latest_payment.description
.group.navform
%p= t(:Acts_on_selected)
- if current_user.clubs_permission? || current_user.graduations_permission?(@club)
= submit_tag t(:Register_Graduation) + " →", :name => "bulk_graduations", :class => "button", :id => "bulk_graduations"
+ = submit_tag t(:Send_Message) + " →", :name => "bulk_message", :class => "button", :id => "bulk_message"
diff --git a/config/locales/en.yml b/config/locales/en.yml
index c74eeab..cfa2ae1 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,186 +1,194 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Logout
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Edit Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
Last_logged_in: Last logged in
+ Body_text: Body text
+ Send: Send
+ Subject: Subject
+ From: From
+ Back: Back
+ Message_sent_to: Message sent to
+ Couldnt_send_to: Couldn't send to
+ because_no_email: because they don't have an email address.
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index c41dd3b..77f1529 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,273 +1,281 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
Last_logged_in: Senaste inloggning
+ Body_text: Brödtext
+ Send: Skicka
+ Subject: Ãrende
+ From: Från
+ Back: Tillbaka
+ Message_sent_to: Meddelandet skickades till
+ Couldnt_send_to: Kunde inte skicka meddelande till
+ because_no_email: eftersom de inte har en epostadress.
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/config/routes.rb b/config/routes.rb
index 05b99af..81cec72 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,80 +1,81 @@
ActionController::Routing::Routes.draw do |map|
# For debugging, check validations
map.validate 'validate', :controller => 'application', :action => 'validate'
map.edit_site 'edit_site_settings', :controller => 'application', :action => 'edit_site_settings'
map.update_site 'update_site_settings', :controller => 'application', :action => 'update_site_settings'
# Bulk operations
map.connect 'students/bulkoperations', :controller => 'students', :action => 'bulk_operations'
map.connect 'graduations/new_bulk', :controller => 'graduations', :action => 'new_bulk'
map.connect 'graduations/update_bulk', :controller => 'graduations', :action => 'update_bulk'
map.connect 'payments/new_bulk', :controller => 'payments', :action => 'new_bulk'
map.connect 'payments/update_bulk', :controller => 'payments', :action => 'update_bulk'
# Clubs, students and subresources
map.resources :clubs, :shallow => true do |club|
club.resources :students, :collection => { :filter => :post } do |student|
student.resources :payments
student.resources :graduations
end
end
map.resources :students, :only => :index
# Other singular resources
map.resources :administrators
map.resources :groups
map.resources :mailing_lists
+ map.resources :messages
# For login and logout
map.resource :user_session
# Password reset
map.resources :password_resets
# Display club list at /
map.root :controller => :clubs
# map.root :controller => "user_sessions", :action => "new"
# 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
|
calmh/Register
|
e14aafb126f6d9e67c14fad27685c9571e110928
|
Fix exporting of filtered views.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 919552d..2aa8751 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,251 +1,251 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
def initialize
@club_id = Club.all.map { |c| c.id }
@sort_field = 'fname'
@sort_order = 'up'
end
def conditions
variables = []
conditions = []
if @club_id.respond_to?(:each)
conditions << "club_id in (?)"
variables << @club_id
elsif !@club_id.nil?
conditions << "club_id = ?"
variables << @club_id
end
if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
if @sort_field.nil? || @sort_order.nil?
return students
else
return students.sort do |a, b|
af = a.send(@sort_field)
bf = b.send(@sort_field)
if !af.nil? && !bf.nil?
r = af <=> bf
elsif af.nil? && !bf.nil?
r = -1
elsif !af.nil? && bf.nil?
r = 1
else
r = 0
end
r = -r if @sort_order == 'down'
r
end
end
end
def filter(students)
matched = students
if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if !@group_id.nil?
matched = matched.select { |s| s.group_ids.include? @group_id }
end
if @only_active
matched = matched.select { |s| s.active? }
end
return sort(matched)
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
before_filter :load_searchparams, :only => [ :index ]
def index
if !params[:club_id].blank?
@club = Club.find(params[:club_id])
@searchparams.club_id = @club.id
@displayPaymentField = true
@displayClubField = false
else
@clubs = Club.all
@displayPaymentField = false
@displayClubField = true
end
@students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv do
- if require_export_permission(@club)
+ if @club.nil? || require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
return
end
end
end
end
def load_searchparams
@searchparams = SearchParams.new
@searchparams.group_id = params[:gi].to_i unless params[:gi].blank?
@searchparams.grade = params[:gr].to_i unless params[:gr].blank?
@searchparams.title_id = params[:ti].to_i unless params[:ti].blank?
@searchparams.board_position_id = params[:bp].to_i unless params[:bp].blank?
@searchparams.club_position_id = params[:cp].to_i unless params[:cp].blank?
@searchparams.only_active = params[:a].to_i unless params[:a].blank?
@searchparams.sort_field = params[:c] unless params[:c].blank?
@searchparams.sort_order = params[:d] unless params[:d].blank?
if params.key? :ci
@searchparams.club_id = params[:ci].map{|x| x.to_i}
end
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/views/clubs/_sidebar.html.erb b/app/views/clubs/_sidebar.html.erb
deleted file mode 100644
index def7c67..0000000
--- a/app/views/clubs/_sidebar.html.erb
+++ /dev/null
@@ -1,39 +0,0 @@
-<% if current_user.clubs_permission? && controller.controller_name == "clubs" && controller.action_name == "index" -%>
-<div class="block">
- <h3><%=t(:Links)%></h3>
- <ul class="navigation">
- <li><%= link_to t(:New_Club), new_club_path %></li>
- </ul>
-</div>
-
-<div class="block">
- <h3><%=t(:Statistics)%></h3>
- <div class="content">
- <p>
- <%=t(:Num_Clubs)%>: <%[email protected]%><br/>
- </p>
- </div>
-</div>
-<% elsif controller.controller_name != 'clubs' && controller.action_name != 'new' && controller.action_name != "create" -%>
-<% if [email protected]? %>
-<div class="block">
- <h3><%=t(:Links)%> <%= t(:for) %> <%= h(@club.name) %></h3>
- <ul class="navigation">
- <% if controller.action_name != "index" && controller.action_name != "filter" -%>
- <li><%= link_to t(:Show), club_path(@club) %></li>
- <% end %>
- <% if current_user.clubs_permission? && controller.action_name != "edit" -%>
- <li><%= link_to t(:Edit), edit_club_path(@club) %></li>
- <% end %>
- <% if current_user.edit_club_permission?(@club) %>
- <li><%= link_to t(:New_Student), new_club_student_path(@club) %></li>
- <% end %>
- <% if current_user.export_permission?(@club) -%>
- <li><%= link_to t(:Export_as_CSV), request.request_uri + ".csv" %></li>
- <% end -%>
- </ul>
-</div>
-<% end %>
-<%= render :partial => 'students/searchbar' %>
-<%= render :partial => "students/statistics" %>
-<% end -%>
diff --git a/app/views/clubs/_sidebar.html.haml b/app/views/clubs/_sidebar.html.haml
new file mode 100644
index 0000000..e97c235
--- /dev/null
+++ b/app/views/clubs/_sidebar.html.haml
@@ -0,0 +1,32 @@
+- if current_user.clubs_permission? && controller.controller_name == "clubs" && controller.action_name == "index"
+ .block
+ %h3= t(:Links)
+ %ul.navigation
+ %li= link_to t(:New_Club), new_club_path
+ .block
+ %h3= t(:Statistics)
+ .content
+ %p= t(:Num_Clubs) + ":" + @clubs.length.to_s
+ %br
+- elsif controller.controller_name != 'clubs' && controller.action_name != 'new' && controller.action_name != "create"
+ - if [email protected]?
+ .block
+ %h3
+ = t(:Links) + " " + t(:for) + " " + h(@club.name)
+ %ul.navigation
+ - if controller.action_name != "index" && controller.action_name != "filter"
+ %li= link_to t(:Show), club_path(@club)
+ - if current_user.clubs_permission? && controller.action_name != "edit"
+ %li= link_to t(:Edit), edit_club_path(@club)
+ - if current_user.edit_club_permission?(@club)
+ %li= link_to t(:New_Student), new_club_student_path(@club)
+ - if current_user.export_permission?(@club)
+ %li= link_to t(:Export_as_CSV), request.parameters.merge(:format => :csv)
+ - else
+ .block
+ %h3
+ = t(:Links)
+ %ul.navigation
+ %li= link_to t(:Export_as_CSV), request.parameters.merge(:format => :csv)
+ = render :partial => 'students/searchbar'
+ = render :partial => 'students/statistics'
|
calmh/Register
|
d5353977421f4f8dafb6fe3263db93f844229a6e
|
Simplify searching and sorting behaviour
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 8427501..919552d 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,242 +1,251 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
attr_accessor :sort_field
attr_accessor :sort_order
- def initialize(params)
- @group_id = -100
- @grade = -100
- @club_id = Club.find(:all).map { |c| c.id }
- @title_id = -100
- @board_position_id = -100
- @club_position_id = -100
- @only_active = false
- @sort_order = "up"
- @sort_field = :fname
-
- if params.key? :searchparams
- @group_id = params[:searchparams][:group_id].to_i
- @grade = params[:searchparams][:grade].to_i
- @title_id = params[:searchparams][:title_id].to_i
- @board_position_id = params[:searchparams][:board_position_id].to_i
- @club_position_id = params[:searchparams][:club_position_id].to_i
- @only_active = (params[:searchparams][:only_active] == '1')
- if params[:searchparams].has_key? :club_id
- @club_id = params[:searchparams][:club_id].map{|x| x.to_i}
- end
- end
-
- @sort_field = params[:c] if params.key? :c
- @sort_order = params[:d] if params.key? :d
+ def initialize
+ @club_id = Club.all.map { |c| c.id }
+ @sort_field = 'fname'
+ @sort_order = 'up'
end
def conditions
variables = []
conditions = []
- conditions << "club_id in (?)"
- variables << @club_id
- if title_id != -100
+
+ if @club_id.respond_to?(:each)
+ conditions << "club_id in (?)"
+ variables << @club_id
+ elsif !@club_id.nil?
+ conditions << "club_id = ?"
+ variables << @club_id
+ end
+
+ if !@title_id.nil?
conditions << "title_id = ?"
variables << @title_id
end
- if board_position_id != -100
+
+ if !@board_position_id.nil?
conditions << "board_position_id = ?"
variables << @board_position_id
end
- if club_position_id != -100
+
+ if !@club_position_id.nil?
conditions << "club_position_id = ?"
variables << @club_position_id
end
+
return [ conditions.join(" AND ") ] + variables
end
def sort(students)
- students.sort do |a, b|
- af = a.send(@sort_field)
- bf = b.send(@sort_field)
- if !af.nil? && !bf.nil?
- r = af <=> bf
- elsif af.nil? && !bf.nil?
- r = -1
- elsif !af.nil? && bf.nil?
- r = 1
- else
- r = 0
+ if @sort_field.nil? || @sort_order.nil?
+ return students
+ else
+ return students.sort do |a, b|
+ af = a.send(@sort_field)
+ bf = b.send(@sort_field)
+ if !af.nil? && !bf.nil?
+ r = af <=> bf
+ elsif af.nil? && !bf.nil?
+ r = -1
+ elsif !af.nil? && bf.nil?
+ r = 1
+ else
+ r = 0
+ end
+ r = -r if @sort_order == 'down'
+ r
end
- r = -r if @sort_order == 'down'
- r
end
end
def filter(students)
matched = students
- if grade != -100
+
+ if [email protected]?
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
- if group_id != -100
- matched = matched.select { |s| s.group_ids.include? group_id }
+
+ if !@group_id.nil?
+ matched = matched.select { |s| s.group_ids.include? @group_id }
end
- if only_active
+
+ if @only_active
matched = matched.select { |s| s.active? }
end
+
return sort(matched)
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
+ before_filter :load_searchparams, :only => [ :index ]
def index
- @searchparams = SearchParams.new(params)
- @club = Club.find(params[:club_id])
- @students = @searchparams.filter @club.students.all_inclusive.find :all, :conditions => @searchparams.conditions
+ if !params[:club_id].blank?
+ @club = Club.find(params[:club_id])
+ @searchparams.club_id = @club.id
+ @displayPaymentField = true
+ @displayClubField = false
+ else
+ @clubs = Club.all
+ @displayPaymentField = false
+ @displayClubField = true
+ end
+ @students = @searchparams.filter Student.all_inclusive(@searchparams.conditions)
respond_to do |format|
format.html # index.html
format.csv do
if require_export_permission(@club)
- send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=#{@club.name}.csv")
+ send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=export.csv")
return
end
end
end
end
- def filter
- @searchparams = SearchParams.new(params)
- @club = Club.find(params[:club_id])
- @students = @searchparams.filter @club.students.all_inclusive.find(:all, :conditions => @searchparams.conditions)
- end
-
- def search
- @searchparams = SearchParams.new(params)
- @clubs = Club.find(:all, :order => :name)
- @students = @searchparams.filter Student.all_inclusive.find(:all, :conditions => @searchparams.conditions)
+ def load_searchparams
+ @searchparams = SearchParams.new
+ @searchparams.group_id = params[:gi].to_i unless params[:gi].blank?
+ @searchparams.grade = params[:gr].to_i unless params[:gr].blank?
+ @searchparams.title_id = params[:ti].to_i unless params[:ti].blank?
+ @searchparams.board_position_id = params[:bp].to_i unless params[:bp].blank?
+ @searchparams.club_position_id = params[:cp].to_i unless params[:cp].blank?
+ @searchparams.only_active = params[:a].to_i unless params[:a].blank?
+ @searchparams.sort_field = params[:c] unless params[:c].blank?
+ @searchparams.sort_order = params[:d] unless params[:d].blank?
+ if params.key? :ci
+ @searchparams.club_id = params[:ci].map{|x| x.to_i}
+ end
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index 98b5f7a..1234b6e 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,125 +1,127 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => REQUIRE_PERSONAL_NUMBER
validates_uniqueness_of :personal_number, :if => Proc.new { |s| !s.personal_number.blank? && s.personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/ }
validate :check_personal_number
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
- named_scope :all_inclusive, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ]
+ named_scope :all_inclusive, lambda { |c| {
+ :conditions => c, :include => [ { :graduations => :grade_category }, :payments, :club, :groups, :main_interest, :board_position, :club_position, :title ]
+ } }
acts_as_authentic do |c|
c.validate_password_field = true
c.require_password_confirmation = true
c.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..-1].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
sum % 10
end
def check_personal_number
if !personal_number.blank?
errors.add(:personal_number, :invalid) if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d(-\d\d\d\d)?$/
if personal_number.length == 13:
errors.add(:personal_number, :incorrect_check_digit) if luhn != 0
end
end
end
def personal_number=(value)
value = $1 + "-" + $2 if value =~ /^(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(19\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(20\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
p = Payment.new
p.amount = 0
p.received = created_at
p.description = "Start"
return p
end
end
def current_grade
if graduations.blank?
return nil
else
in_main_interest = graduations.select { |g| g.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return graduations[0]
end
end
end
def active?
if payments.blank?
return Time.now - created_at < 86400 * 45
else
return Time.now - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] unless self[:gender].blank?
return 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
d = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today-d) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |g| g.identifier }.join(", ")
end
end
diff --git a/app/views/application/_links.html.haml b/app/views/application/_links.html.haml
index 8a96f08..7f5f11f 100644
--- a/app/views/application/_links.html.haml
+++ b/app/views/application/_links.html.haml
@@ -1,22 +1,22 @@
-- active = active_string(controller.controller_name == 'clubs' || (controller.controller_name == "students" && controller.action_name != "search"))
+- active = active_string(controller.controller_name == 'clubs' || (controller.controller_name == "students" && [email protected]? ))
%li.first{:class => active}= link_to t(:Club_List), clubs_path
- if current_user.clubs_permission?
- - active = active_string(controller.controller_name == 'students' && controller.action_name == "search")
- %li{:class => active}= link_to t(:Search_Students), search_path
+ - active = active_string(controller.controller_name == 'students' && @club.blank? )
+ %li{:class => active}= link_to t(:Search_Students), students_path
- if current_user.groups_permission?
- active = active_string(controller.controller_name == 'groups')
%li{:class => active}= link_to t(:Group_List), groups_path
- if current_user.mailinglists_permission?
- active = active_string(controller.controller_name == 'mailing_lists')
%li{:class => active}= link_to t(:Mailing_Lists), mailing_lists_path
- if current_user.users_permission?
- active = active_string(controller.controller_name == 'administrators')
%li{:class => active}= link_to t(:User_List), administrators_path
- if current_user.site_permission?
- active = active_string(controller.controller_name == 'application')
%li{:class => active}= link_to t(:Edit_Site), edit_site_path
diff --git a/app/views/clubs/_sidebar.html.erb b/app/views/clubs/_sidebar.html.erb
index 8388e77..def7c67 100644
--- a/app/views/clubs/_sidebar.html.erb
+++ b/app/views/clubs/_sidebar.html.erb
@@ -1,37 +1,39 @@
<% if current_user.clubs_permission? && controller.controller_name == "clubs" && controller.action_name == "index" -%>
<div class="block">
<h3><%=t(:Links)%></h3>
<ul class="navigation">
<li><%= link_to t(:New_Club), new_club_path %></li>
</ul>
</div>
<div class="block">
<h3><%=t(:Statistics)%></h3>
<div class="content">
<p>
<%=t(:Num_Clubs)%>: <%[email protected]%><br/>
</p>
</div>
</div>
<% elsif controller.controller_name != 'clubs' && controller.action_name != 'new' && controller.action_name != "create" -%>
+<% if [email protected]? %>
<div class="block">
<h3><%=t(:Links)%> <%= t(:for) %> <%= h(@club.name) %></h3>
<ul class="navigation">
<% if controller.action_name != "index" && controller.action_name != "filter" -%>
<li><%= link_to t(:Show), club_path(@club) %></li>
<% end %>
<% if current_user.clubs_permission? && controller.action_name != "edit" -%>
<li><%= link_to t(:Edit), edit_club_path(@club) %></li>
<% end %>
<% if current_user.edit_club_permission?(@club) %>
<li><%= link_to t(:New_Student), new_club_student_path(@club) %></li>
<% end %>
<% if current_user.export_permission?(@club) -%>
<li><%= link_to t(:Export_as_CSV), request.request_uri + ".csv" %></li>
<% end -%>
</ul>
</div>
+<% end %>
<%= render :partial => 'students/searchbar' %>
<%= render :partial => "students/statistics" %>
<% end -%>
diff --git a/app/views/students/_list.html.erb b/app/views/students/_list.html.erb
deleted file mode 100644
index 56ed76f..0000000
--- a/app/views/students/_list.html.erb
+++ /dev/null
@@ -1,51 +0,0 @@
-<% form_tag :controller => 'students', :action => 'bulk_operations', :class => "form", :method => "post" do %>
-<table class="table lesspadding">
- <tr>
- <th class="first"> </th>
- <th><%= sort_link t(:Name), :fname %></th>
- <% if @displayClubField -%>
- <th><%= sort_link t(:Club), :club %></th>
- <% end -%>
- <th><%= sort_link t(:Main_Interest), :main_interest %></th>
- <th><%=t(:Groups)%></th>
- <th><%= sort_link t(:Personal_Num), :personal_number %></th>
- <% if @displayPaymentField %>
- <th><%= sort_link t(:Grade), :current_grade %></th>
- <th class="last"><%= sort_link t(:Latest_Payment), :latest_payment %>
- <% else %>
- <th class="last"><%= sort_link t(:Grade), :current_grade %></th>
- <% end %>
- </tr>
- <% @students.each do |student| -%>
- <tr class="<%= cycle("odd", "even") %>">
- <td><%= check_box_tag "selected_students[]", student.id, false, { :id => 'selected_students_' + student.id.to_s } %></td>
- <td><%= link_to student.name, student_path(student) %></td>
- <% if @displayClubField -%>
- <td><%= link_to student.club.name, club_path(student.club) %></td>
- <% end -%>
- <td><%= student.main_interest.category %></td>
- <td><%= student.groups.map{ |g| g.identifier }.join(", ") %></td>
- <td><%= student.personal_number %></td>
- <td><%= grade_str(student.current_grade) %></td>
- <% if @displayPaymentField %>
- <td class="student-<%= student.active? ? 'active' :
- 'inactive' %>"><%=h student.latest_payment.description %></td>
- <% end %>
- </tr>
- <% end -%>
- </table>
- <div class="group navform">
- <p><%= t(:Acts_on_selected) %></p>
- <!--
- <%= submit_tag t(:Send_Message) + " →", :name => "bulk_message", :class => "button" %>
- -->
- <% if current_user.clubs_permission? || current_user.graduations_permission?(@club) %>
- <%= submit_tag t(:Register_Graduation) + " →", :name => "bulk_graduations", :class => "button", :id => "bulk_graduations" %>
- <% end %>
- <!-->
- <% if @club && current_user.payments_permission?(@club) %>
- <%= submit_tag t(:Register_Payment) + " →", :name => "bulk_payments", :class => "button", :id => "bulk_payments" %>
- <% end %>
- -->
- </div>
- <% end -%>
diff --git a/app/views/students/_list.html.haml b/app/views/students/_list.html.haml
new file mode 100644
index 0000000..5b8ef1a
--- /dev/null
+++ b/app/views/students/_list.html.haml
@@ -0,0 +1,31 @@
+- form_tag :controller => 'students', :action => 'bulk_operations', :class => "form", :method => "post" do
+ %table.table.lesspadding
+ %tr
+ %th.first
+ %th= sort_link t(:Name), :fname
+ - if @displayClubField
+ %th= sort_link t(:Club), :club
+ %th= sort_link t(:Main_Interest), :main_interest
+ %th= t(:Groups)
+ %th= sort_link t(:Personal_Num), :personal_number
+ - if @displayPaymentField
+ %th= sort_link t(:Grade), :current_grade
+ %th.last= sort_link t(:Latest_Payment), :latest_payment
+ - else
+ %th.last= sort_link t(:Grade), :current_grade
+ - @students.each do |student|
+ %tr{ :class => cycle("odd", "even") }
+ %td= check_box_tag "selected_students[]", student.id, false, { :id => 'selected_students_' + student.id.to_s }
+ %td= link_to student.name, student_path(student)
+ - if @displayClubField
+ %td= link_to student.club.name, club_path(student.club)
+ %td= student.main_interest.category
+ %td= student.groups.map{ |g| g.identifier }.join(", ")
+ %td= student.personal_number
+ %td= grade_str(student.current_grade)
+ - if @displayPaymentField
+ %td{ :class => "student-" + (student.active? ? 'active' : 'inactive')}=h student.latest_payment.description
+ .group.navform
+ %p= t(:Acts_on_selected)
+ - if current_user.clubs_permission? || current_user.graduations_permission?(@club)
+ = submit_tag t(:Register_Graduation) + " →", :name => "bulk_graduations", :class => "button", :id => "bulk_graduations"
diff --git a/app/views/students/_searchbar.html.erb b/app/views/students/_searchbar.html.erb
index 319df8b..a3f5672 100644
--- a/app/views/students/_searchbar.html.erb
+++ b/app/views/students/_searchbar.html.erb
@@ -1,51 +1,47 @@
<div class="block">
<h3><%=t(:Search_Parameters)%></h3>
<div class="content">
<p><%=t(:Search_descr)%></p>
- <% if controller.action_name == 'search' -%>
- <% destination = search_path -%>
- <% else -%>
- <% destination = filter_club_students_path(@club.id) -%>
- <% end -%>
-
- <% form_tag destination, :class => "form", :method => "post" do -%>
+ <% form_tag request.parameters, :class => "form", :method => "get" do -%>
+ <%= hidden_field_tag 'c', @searchparams.sort_field %>
+ <%= hidden_field_tag 'd', @searchparams.sort_order %>
<table class="table">
<% if @clubs != nil -%>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Club%>:</td>
<td>
<%- clubs.each do |club| -%>
- <label><%=check_box_tag 'searchparams[club_id][]', club.id, @searchparams.club_id.include?(club.id)%> <%=club.name%><br/></label>
+ <label><%=check_box_tag 'ci[]', club.id, @searchparams.club_id.include?(club.id)%> <%=club.name%><br/></label>
<%- end -%>
</td>
</tr>
<% end -%>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Grade%>:</td>
- <td><%= select "searchparams", "grade", [[ t(:All), -100 ]] + grades.map { |g| [ g.description, g.id ] } %></td>
+ <td><%= select_tag "gr", "<option value=''>" + t(:All) + "</option>" + options_from_collection_for_select(grades, :id, :description, @searchparams.grade) %></td>
</tr>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Group%>:</td>
- <td><%= select "searchparams", "group_id", [[ t(:All), -100 ]] + groups.map { |g| [ g.identifier, g.id ] } %></td>
+ <td><%= select_tag "gi", "<option value=''>" + t(:All) + "</option>" + options_from_collection_for_select(groups, :id, :identifier, @searchparams.group_id) %></td>
</tr>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Title%>:</td>
- <td><%= select "searchparams", "title_id", [[ t(:All), -100 ]] + titles.map { |g| [ g.title, g.id ] } %></td>
+ <td><%= select_tag "ti", "<option value=''>" + t(:All) + "</option>" + options_from_collection_for_select(titles, :id, :title, @searchparams.title_id) %></td>
</tr>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Board_Position%>:</td>
- <td><%= select "searchparams", "board_position_id", [[ t(:All), -100 ]] + board_positions.map { |g| [ g.position, g.id ] } %></td>
+ <td><%= select_tag "bp", "<option value=''>" + t(:All) + "</option>" + options_from_collection_for_select(board_positions, :id, :position, @searchparams.board_position_id) %></td>
</tr>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Club_Position%>:</td>
- <td><%= select "searchparams", "club_position_id", [[ t(:All), -100 ]] + club_positions.map { |g| [ g.position, g.id ] } %></td>
+ <td><%= select_tag "cp", "<option value=''>" + t(:All) + "</option>" + options_from_collection_for_select(club_positions, :id, :position, @searchparams.club_position_id) %></td>
</tr>
<tr class="<%=cycle('even','odd')%>">
<td><%=t:Only_Active%>:</td>
- <td><label><%=check_box_tag 'searchparams[only_active]', '1', @searchparams.only_active %></label></td>
+ <td><label><%=check_box_tag 'a', '1', @searchparams.only_active %></label></td>
</tr>
</table>
<%= submit_tag t(:Search) %>
<% end -%>
</div>
</div>
diff --git a/app/views/students/filter.html.erb b/app/views/students/filter.html.erb
deleted file mode 100644
index 9b15a4c..0000000
--- a/app/views/students/filter.html.erb
+++ /dev/null
@@ -1,18 +0,0 @@
-<div class="block">
- <div class="secondary-navigation">
- <ul>
- <li class="first"><%= link_to t(:Club_List), clubs_path %></li>
- <li class="active last"><%= link_to h(@club.name), club_path(@club) %></li>
- </ul>
- <div class="clear"></div>
- </div>
- <div class="content">
- <div class="inner">
- <h2><%=t(:Students)%></h2>
- <% @displayPaymentField = true %>
- <%= render :partial => 'list' %>
- </div>
- </div>
-</div>
-
-<% content_for :sidebar, render(:partial => 'clubs/sidebar') -%>
diff --git a/app/views/students/index.html.haml b/app/views/students/index.html.haml
index 973a77d..bd52441 100644
--- a/app/views/students/index.html.haml
+++ b/app/views/students/index.html.haml
@@ -1,13 +1,15 @@
.block
.secondary-navigation
%ul
- %li.first= link_to t(:Club_List), clubs_path
- %li.active.last= link_to h(@club.name), club_path(@club)
+ - if [email protected]?
+ %li.first= link_to t(:Club_List), clubs_path
+ %li.active.last= link_to h(@club.name), club_path(@club)
+ - else
+ %li.first.active.last= link_to t(:Search_Students), students_path
.clear
.content
.inner
%h2= t(:Students)
- - @displayPaymentField = true
= render :partial => 'list'
= content_for :sidebar, render(:partial => 'clubs/sidebar')
diff --git a/app/views/students/search.html.erb b/app/views/students/search.html.erb
deleted file mode 100644
index 0883717..0000000
--- a/app/views/students/search.html.erb
+++ /dev/null
@@ -1,17 +0,0 @@
-<div class="block">
- <div class="secondary-navigation">
- <ul>
- <li class="first active last"><%= link_to t(:Students), search_path %></li>
- </ul>
- <div class="clear"></div>
- </div>
- <div class="content">
- <div class="inner">
- <h2><%=t(:Students)%></h2>
- <% @displayClubField = true %>
- <%= render :partial => 'list' %>
- </div>
- </div>
-</div>
-
-<% content_for :sidebar, render(:partial => 'searchbar') + render(:partial => "statistics") %>
diff --git a/config/routes.rb b/config/routes.rb
index c8fb964..05b99af 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,80 +1,80 @@
ActionController::Routing::Routes.draw do |map|
# For debugging, check validations
map.validate 'validate', :controller => 'application', :action => 'validate'
map.edit_site 'edit_site_settings', :controller => 'application', :action => 'edit_site_settings'
map.update_site 'update_site_settings', :controller => 'application', :action => 'update_site_settings'
# Bulk operations
- map.search 'students/search', :controller => 'students', :action => 'search'
map.connect 'students/bulkoperations', :controller => 'students', :action => 'bulk_operations'
map.connect 'graduations/new_bulk', :controller => 'graduations', :action => 'new_bulk'
map.connect 'graduations/update_bulk', :controller => 'graduations', :action => 'update_bulk'
map.connect 'payments/new_bulk', :controller => 'payments', :action => 'new_bulk'
map.connect 'payments/update_bulk', :controller => 'payments', :action => 'update_bulk'
# Clubs, students and subresources
map.resources :clubs, :shallow => true do |club|
club.resources :students, :collection => { :filter => :post } do |student|
student.resources :payments
student.resources :graduations
end
end
+ map.resources :students, :only => :index
# Other singular resources
map.resources :administrators
map.resources :groups
map.resources :mailing_lists
# For login and logout
map.resource :user_session
# Password reset
map.resources :password_resets
# Display club list at /
map.root :controller => :clubs
# map.root :controller => "user_sessions", :action => "new"
# 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/test/integration/viewing_test.rb b/test/integration/viewing_test.rb
index 6c2ea64..4ebaac3 100644
--- a/test/integration/viewing_test.rb
+++ b/test/integration/viewing_test.rb
@@ -1,66 +1,66 @@
require 'test_helper'
class ViewingTest < ActionController::IntegrationTest
fixtures :all
test "verify student sorting" do
log_in
click_link "Klubbar"
click_link "Brålanda"
assert_contain /Agaton.*Amalia.*Emma/m
click_link "Sök tränande"
assert_contain /Baran.*Devin.*Edgar.*Marielle.*Nino.*Svante/m
end
test "verify only active filtering" do
log_in
click_link "Klubbar"
click_link "Edsvalla"
assert_contain "Baran"
assert_contain "Razmus"
- check "searchparams[only_active]"
+ check "a"
click_button "Sök"
assert_contain "Razmus"
assert_not_contain "Baran"
click_button "Sök"
assert_contain "Razmus"
assert_not_contain "Baran"
- uncheck "searchparams[only_active]"
+ uncheck "a"
click_button "Sök"
assert_contain "Baran"
assert_contain "Razmus"
end
test "verify student search" do
log_in
assert_contain "Klubbar"
assert_contain "Grupper"
assert_contain "Användare"
assert_contain "Sök tränande"
assert_contain "Ny klubb"
click_link "Sök tränande"
assert_contain " 13 tränande"
select "Instruktörer"
click_button "Sök"
assert_contain " 2 tränande"
- check "searchparams_only_active"
+ check "a"
click_button "Sök"
assert_contain " 1 tränande"
- uncheck "searchparams_only_active"
+ uncheck "a"
click_button "Sök"
assert_contain " 2 tränande"
end
end
|
calmh/Register
|
f35f522cc2d289d5e7876d371c7da4c502bbc8ca
|
View latest log in on users summary.
|
diff --git a/app/views/administrators/index.html.erb b/app/views/administrators/index.html.erb
deleted file mode 100644
index 46910ce..0000000
--- a/app/views/administrators/index.html.erb
+++ /dev/null
@@ -1,37 +0,0 @@
-<div class="block">
- <div class="secondary-navigation">
- <ul>
- <li class="active first last"><%= link_to t(:Users), administrators_path %></li>
- </ul>
- <div class="clear"></div>
- </div>
- <div class="content">
- <h2 class="title"><%=t:Users%></h2>
- <div class="inner">
- <table class="table">
- <tr>
- <th><%=t:Login%></th>
- <th class="last"><%=t:Name%></th>
- </tr>
- <% @admins.each do |admin| -%>
- <tr class="<%= cycle("odd", "even") %>">
- <td>
- <%= link_to admin.login, administrator_path(admin) %>
- </td>
- <td>
- <%= (admin.fname or "") + " " + (admin.sname or "") %>
- </td>
- </tr>
- <% end -%>
- </table>
- <div class="actions-bar">
- <div class="actions">
- </div>
-
- <div class="clear"></div>
- </div>
- </div>
- </div>
-</div>
-
-<% content_for :sidebar, render(:partial => 'sidebar') -%>
diff --git a/app/views/administrators/index.html.haml b/app/views/administrators/index.html.haml
new file mode 100644
index 0000000..93e3394
--- /dev/null
+++ b/app/views/administrators/index.html.haml
@@ -0,0 +1,22 @@
+.block
+ .secondary-navigation
+ %ul
+ %li.active.first.las= link_to t(:Users), administrators_path
+ .clear
+ .content
+ %h2.title= t:Users
+ .inner
+ %table.table
+ %tr
+ %th.first= t:Login
+ %th= t:Name
+ %th= t:Last_logged_in
+ - @admins.each do |admin|
+ %tr{ :class => cycle("odd", "even") }
+ %td= link_to admin.login, administrator_path(admin)
+ %td= (admin.fname or "") + " " + (admin.sname or "")
+ %td= admin.current_login_at or admin.last_login_at
+ .clear
+
+= content_for :sidebar, render(:partial => 'sidebar')
+
diff --git a/config/locales/en.yml b/config/locales/en.yml
index c9c2d64..c74eeab 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,185 +1,186 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Logout
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Edit Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
View_source: View source
+ Last_logged_in: Last logged in
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 9a755b8..c41dd3b 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,272 +1,273 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
View_source: Se källkod
+ Last_logged_in: Senaste inloggning
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
|
calmh/Register
|
4254acb430bd8c0c3a942c39b5dc3837c3f29dd2
|
View source link
|
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index 068210a..3b8cbf5 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,49 +1,51 @@
!!!
%html
- cache('layout_header') do
%head
%title= get_config(:site_name)
= stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style"
= stylesheet_link_tag 'web_app_theme_override'
%body
#container
#header
%h1
%a{ :href => root_path }= get_config(:site_name)
#user-navigation
%ul
- if current_user
- if current_user.type == 'Administrator'
%li= link_to t(:Profile), administrator_path(current_user)
%li=link_to t(:Logout), user_session_path, :method => :delete, :class => "logout"
- for locale in I18n.available_locales do
- if locale.to_s != I18n.locale.to_s
%li= link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s
.clear
- if ! ['user_sessions', 'password_resets'].include?(controller.controller_name)
#main-navigation
%ul
= render :partial => 'application/links'
.clear
#wrapper
.flash
- flash.each do |type, message|
%div{ :class => "message " + type.to_s }
%p= message
#main
= yield
- cache('layout_footer') do
#footer
.block
%p
#{t(:Register)} v#{version}
 | 
#{COPYRIGHT}
 | 
= link_to t(:Report_bug), 'http://github.com/calmh/Register/issues'
+  | 
+ = link_to t(:View_source), 'http://github.com/calmh/Register'
#sidebar= yield :sidebar
.clear
diff --git a/config/locales/en.yml b/config/locales/en.yml
index fac39dc..c9c2d64 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,184 +1,185 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Logout
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Edit Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
Report_bug: Report bug
+ View_source: View source
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 770c39d..9a755b8 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,271 +1,272 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
Report_bug: Rapportera felaktighet
+ View_source: Se källkod
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
|
calmh/Register
|
7ceda509517065a14ba13d5ba5aa4cf4e846a4fa
|
Report bug link
|
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
index a8470c2..068210a 100644
--- a/app/views/layouts/application.html.haml
+++ b/app/views/layouts/application.html.haml
@@ -1,44 +1,49 @@
!!!
%html
- cache('layout_header') do
%head
%title= get_config(:site_name)
= stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style"
= stylesheet_link_tag 'web_app_theme_override'
%body
#container
#header
%h1
%a{ :href => root_path }= get_config(:site_name)
#user-navigation
%ul
- if current_user
- if current_user.type == 'Administrator'
%li= link_to t(:Profile), administrator_path(current_user)
%li=link_to t(:Logout), user_session_path, :method => :delete, :class => "logout"
- for locale in I18n.available_locales do
- if locale.to_s != I18n.locale.to_s
%li= link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s
.clear
- if ! ['user_sessions', 'password_resets'].include?(controller.controller_name)
#main-navigation
%ul
= render :partial => 'application/links'
.clear
#wrapper
.flash
- flash.each do |type, message|
%div{ :class => "message " + type.to_s }
%p= message
#main
= yield
- cache('layout_footer') do
#footer
.block
- %p #{t(:Register)} v#{version}  |  #{COPYRIGHT}
+ %p
+ #{t(:Register)} v#{version}
+  | 
+ #{COPYRIGHT}
+  | 
+ = link_to t(:Report_bug), 'http://github.com/calmh/Register/issues'
#sidebar= yield :sidebar
.clear
diff --git a/config/locales/en.yml b/config/locales/en.yml
index bedcbe6..fac39dc 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,183 +1,184 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Logout
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Edit Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
+ Report_bug: Report bug
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index ec5b2d6..770c39d 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,270 +1,271 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
+ Report_bug: Rapportera felaktighet
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: Användarnamn
email: Epostadress
password: Lösenord
remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/public/stylesheets/sass/web_app_theme_override.sass b/public/stylesheets/sass/web_app_theme_override.sass
index ba3f570..3ccebd3 100644
--- a/public/stylesheets/sass/web_app_theme_override.sass
+++ b/public/stylesheets/sass/web_app_theme_override.sass
@@ -1,29 +1,31 @@
body
line-height: 1.5em
td
&.student-active
background-color: #d0ffd0
&.student-inactive
background-color: #ffd0d0
th
&.first, &.last
width: inherit!important
td
width: inherit!important
.fullwidth
width: 100%
.table td
padding: 6px 5px 4px 5px
.lesspadding td
padding: 3px 5px 2px 5px
#footer
font-size: .8em
+ a
+ color: inherit
|
calmh/Register
|
2c5cc7f658f6a98b79871fe8a849f7f009676aba
|
First attempt at sorting by column headers.
|
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index f5b749e..8427501 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,229 +1,242 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
+ attr_accessor :sort_field
+ attr_accessor :sort_order
def initialize(params)
@group_id = -100
@grade = -100
@club_id = Club.find(:all).map { |c| c.id }
@title_id = -100
@board_position_id = -100
@club_position_id = -100
@only_active = false
+ @sort_order = "up"
+ @sort_field = :fname
if params.key? :searchparams
@group_id = params[:searchparams][:group_id].to_i
@grade = params[:searchparams][:grade].to_i
@title_id = params[:searchparams][:title_id].to_i
@board_position_id = params[:searchparams][:board_position_id].to_i
@club_position_id = params[:searchparams][:club_position_id].to_i
@only_active = (params[:searchparams][:only_active] == '1')
if params[:searchparams].has_key? :club_id
@club_id = params[:searchparams][:club_id].map{|x| x.to_i}
end
end
+
+ @sort_field = params[:c] if params.key? :c
+ @sort_order = params[:d] if params.key? :d
end
def conditions
variables = []
conditions = []
conditions << "club_id in (?)"
variables << @club_id
if title_id != -100
conditions << "title_id = ?"
variables << @title_id
end
if board_position_id != -100
conditions << "board_position_id = ?"
variables << @board_position_id
end
if club_position_id != -100
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
+ def sort(students)
+ students.sort do |a, b|
+ af = a.send(@sort_field)
+ bf = b.send(@sort_field)
+ if !af.nil? && !bf.nil?
+ r = af <=> bf
+ elsif af.nil? && !bf.nil?
+ r = -1
+ elsif !af.nil? && bf.nil?
+ r = 1
+ else
+ r = 0
+ end
+ r = -r if @sort_order == 'down'
+ r
+ end
+ end
+
def filter(students)
matched = students
if grade != -100
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if group_id != -100
matched = matched.select { |s| s.group_ids.include? group_id }
end
if only_active
matched = matched.select { |s| s.active? }
end
- return matched
- end
-
- def find_all
- @students = Student.find(:all, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ], :conditions => conditions, :order => "fname, sname")
- @students = filter(@students)
- return @students
- end
-
- def find_in_club(club)
- @students = club.students.find(:all, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ], :conditions => conditions, :order => "fname, sname")
- @students = filter(@students)
- return @students
+ return sort(matched)
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
def index
@searchparams = SearchParams.new(params)
@club = Club.find(params[:club_id])
- @students = @searchparams.find_in_club(@club)
+ @students = @searchparams.filter @club.students.all_inclusive.find :all, :conditions => @searchparams.conditions
respond_to do |format|
format.html # index.html
format.csv do
if require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=#{@club.name}.csv")
return
end
end
end
end
def filter
@searchparams = SearchParams.new(params)
@club = Club.find(params[:club_id])
- @students = @searchparams.find_in_club(@club)
+ @students = @searchparams.filter @club.students.all_inclusive.find(:all, :conditions => @searchparams.conditions)
end
def search
@searchparams = SearchParams.new(params)
@clubs = Club.find(:all, :order => :name)
- @students = @searchparams.find_all
+ @students = @searchparams.filter Student.all_inclusive.find(:all, :conditions => @searchparams.conditions)
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
# This is an ugly hack that uses the random perishable token as a base password for the user.
@student.reset_perishable_token!
@student.password = @student.password_confirmation = @student.perishable_token
@student.reset_perishable_token!
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 21ec7d3..59dc91d 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,55 +1,61 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def get_config(setting)
SiteSettings.get_setting(setting)
end
def grades
Grade.find(:all, :order => :level)
end
def grade_categories
GradeCategory.find(:all, :order => :category)
end
def titles
Title.find(:all, :order => :level)
end
def board_positions
BoardPosition.find(:all, :order => :id)
end
def club_positions
ClubPosition.find(:all, :order => :id)
end
def grade_str(graduation)
if graduation == nil
return "-"
else
return graduation.grade.description + " (" + graduation.grade_category.category + ")"
end
end
def groups
Group.find(:all, :order => :identifier)
end
def clubs
Club.find(:all, :order => :name)
end
def mailing_lists
MailingList.find(:all, :order => :description)
end
def version
`git describe`.strip.sub(/-(\d+)-g[0-9a-f]+$/, '+\1')
end
def active_string(active)
return 'active' if active
''
end
+
+ def sort_link(title, column, options = {})
+ condition = options[:unless] if options.has_key?(:unless)
+ sort_dir = params[:d] == 'up' ? 'down' : 'up'
+ link_to_unless condition, title, request.parameters.merge( {:c => column, :d => sort_dir} )
+ end
end
diff --git a/app/models/club.rb b/app/models/club.rb
index a444b71..ee3a50b 100644
--- a/app/models/club.rb
+++ b/app/models/club.rb
@@ -1,7 +1,11 @@
class Club < ActiveRecord::Base
has_many :users, :through => :permissions
has_many :students, :order => "fname, sname", :dependent => :destroy
has_many :permissions, :dependent => :destroy
validates_presence_of :name
validates_uniqueness_of :name
+
+ def <=>(b)
+ name <=> b.name
+ end
end
diff --git a/app/models/grade.rb b/app/models/grade.rb
index 3c353d7..ffc7263 100644
--- a/app/models/grade.rb
+++ b/app/models/grade.rb
@@ -1,4 +1,8 @@
class Grade < ActiveRecord::Base
validates_presence_of :description, :level
validates_numericality_of :level
+
+ def <=>(b)
+ level <=> b.level
+ end
end
diff --git a/app/models/grade_category.rb b/app/models/grade_category.rb
index b3b12b8..c7ce5c8 100644
--- a/app/models/grade_category.rb
+++ b/app/models/grade_category.rb
@@ -1,3 +1,7 @@
class GradeCategory < ActiveRecord::Base
validates_presence_of :category
+
+ def <=>(b)
+ category <=> b.category
+ end
end
diff --git a/app/models/graduation.rb b/app/models/graduation.rb
index 2b593d5..86fc1e6 100644
--- a/app/models/graduation.rb
+++ b/app/models/graduation.rb
@@ -1,6 +1,10 @@
class Graduation < ActiveRecord::Base
belongs_to :student
belongs_to :grade
belongs_to :grade_category
validates_presence_of :examiner, :instructor, :graduated, :grade, :grade_category
+
+ def <=>(b)
+ grade <=> b.grade
+ end
end
diff --git a/app/models/payment.rb b/app/models/payment.rb
index 609648b..26dffa0 100644
--- a/app/models/payment.rb
+++ b/app/models/payment.rb
@@ -1,5 +1,9 @@
class Payment < ActiveRecord::Base
belongs_to :student
validates_numericality_of :amount
validates_presence_of :amount, :description, :received
+
+ def <=>(b)
+ received <=> b.received
+ end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index 024fc12..98b5f7a 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,124 +1,125 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => REQUIRE_PERSONAL_NUMBER
validates_uniqueness_of :personal_number, :if => Proc.new { |s| !s.personal_number.blank? && s.personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/ }
validate :check_personal_number
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
+ named_scope :all_inclusive, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ]
acts_as_authentic do |c|
c.validate_password_field = true
c.require_password_confirmation = true
c.validates_length_of_login_field_options = { :in => 2..20 }
end
def luhn
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..-1].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
sum % 10
end
def check_personal_number
if !personal_number.blank?
errors.add(:personal_number, :invalid) if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d(-\d\d\d\d)?$/
if personal_number.length == 13:
errors.add(:personal_number, :incorrect_check_digit) if luhn != 0
end
end
end
def personal_number=(value)
value = $1 + "-" + $2 if value =~ /^(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(19\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(20\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
p = Payment.new
p.amount = 0
p.received = created_at
p.description = "Start"
return p
end
end
def current_grade
if graduations.blank?
return nil
else
in_main_interest = graduations.select { |g| g.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return graduations[0]
end
end
end
def active?
if payments.blank?
return Time.now - created_at < 86400 * 45
else
return Time.now - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] unless self[:gender].blank?
return 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
d = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today-d) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |g| g.identifier }.join(", ")
end
end
diff --git a/app/views/students/_list.html.erb b/app/views/students/_list.html.erb
index 9036a7f..56ed76f 100644
--- a/app/views/students/_list.html.erb
+++ b/app/views/students/_list.html.erb
@@ -1,51 +1,51 @@
<% form_tag :controller => 'students', :action => 'bulk_operations', :class => "form", :method => "post" do %>
<table class="table lesspadding">
<tr>
<th class="first"> </th>
- <th><%=t(:Name)%></th>
+ <th><%= sort_link t(:Name), :fname %></th>
<% if @displayClubField -%>
- <th><%=t(:Club)%></th>
+ <th><%= sort_link t(:Club), :club %></th>
<% end -%>
- <th><%=t(:Main_Interest)%></th>
+ <th><%= sort_link t(:Main_Interest), :main_interest %></th>
<th><%=t(:Groups)%></th>
- <th><%=t(:Personal_Num)%></th>
+ <th><%= sort_link t(:Personal_Num), :personal_number %></th>
<% if @displayPaymentField %>
- <th><%=t(:Grade)%></th>
- <th class="last"><%=t(:Latest_Payment)%>
+ <th><%= sort_link t(:Grade), :current_grade %></th>
+ <th class="last"><%= sort_link t(:Latest_Payment), :latest_payment %>
<% else %>
- <th class="last"><%=t(:Grade)%></th>
+ <th class="last"><%= sort_link t(:Grade), :current_grade %></th>
<% end %>
</tr>
<% @students.each do |student| -%>
<tr class="<%= cycle("odd", "even") %>">
<td><%= check_box_tag "selected_students[]", student.id, false, { :id => 'selected_students_' + student.id.to_s } %></td>
<td><%= link_to student.name, student_path(student) %></td>
<% if @displayClubField -%>
<td><%= link_to student.club.name, club_path(student.club) %></td>
<% end -%>
<td><%= student.main_interest.category %></td>
<td><%= student.groups.map{ |g| g.identifier }.join(", ") %></td>
<td><%= student.personal_number %></td>
<td><%= grade_str(student.current_grade) %></td>
<% if @displayPaymentField %>
<td class="student-<%= student.active? ? 'active' :
'inactive' %>"><%=h student.latest_payment.description %></td>
<% end %>
</tr>
<% end -%>
</table>
<div class="group navform">
<p><%= t(:Acts_on_selected) %></p>
<!--
<%= submit_tag t(:Send_Message) + " →", :name => "bulk_message", :class => "button" %>
-->
<% if current_user.clubs_permission? || current_user.graduations_permission?(@club) %>
<%= submit_tag t(:Register_Graduation) + " →", :name => "bulk_graduations", :class => "button", :id => "bulk_graduations" %>
<% end %>
<!-->
<% if @club && current_user.payments_permission?(@club) %>
<%= submit_tag t(:Register_Payment) + " →", :name => "bulk_payments", :class => "button", :id => "bulk_payments" %>
<% end %>
-->
</div>
<% end -%>
|
calmh/Register
|
e3d48d4aaca7b6d8012821dec9a9ab60b2b90005
|
Fix password reset and login for students.
|
diff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rb
index b4275ab..7a4edf8 100644
--- a/app/controllers/password_resets_controller.rb
+++ b/app/controllers/password_resets_controller.rb
@@ -1,46 +1,55 @@
class PasswordResetsController < ApplicationController
before_filter :load_user_using_perishable_token, :only => [:edit, :update]
before_filter :require_no_user, :only => [ :new, :edit ]
def new
render
end
def create
@user = User.find_by_login_or_email(params[:password_reset][:login])
if @user
@user.deliver_password_reset_instructions!
flash[:notice] = t(:Mailed_reset_instruction)
redirect_to new_user_session_path
else
flash[:notice] = t(:No_user_found)
render :action => :new
end
end
def edit
render
end
def update
- data = params[:student]
- data = params[:administrator] if data.nil?
+ data = nil
+ if params.key? :administrator
+ data = params[:administrator]
+ elsif params.key? :student
+ data = params[:student]
+ end
@user.password = data[:password]
@user.password_confirmation = data[:password_confirmation]
+
if @user.save
flash[:notice] = t(:Password_updated)
- redirect_to root_url
+ if @user.kind_of? Administrator
+ redirect_to edit_administrator_path(@user)
+ else
+ redirect_to edit_student_path(@user)
+ end
else
render :action => :edit
end
end
private
def load_user_using_perishable_token
@user = User.find_using_perishable_token(params[:id])
unless @user
flash[:notice] = t(:Could_not_load_account)
redirect_to root_url
end
end
end
diff --git a/app/controllers/students_controller.rb b/app/controllers/students_controller.rb
index 45b90a1..f5b749e 100644
--- a/app/controllers/students_controller.rb
+++ b/app/controllers/students_controller.rb
@@ -1,223 +1,229 @@
class SearchParams
attr_accessor :group_id
attr_accessor :grade
attr_accessor :club_id
attr_accessor :title_id
attr_accessor :board_position_id
attr_accessor :club_position_id
attr_accessor :only_active
def initialize(params)
@group_id = -100
@grade = -100
@club_id = Club.find(:all).map { |c| c.id }
@title_id = -100
@board_position_id = -100
@club_position_id = -100
@only_active = false
if params.key? :searchparams
@group_id = params[:searchparams][:group_id].to_i
@grade = params[:searchparams][:grade].to_i
@title_id = params[:searchparams][:title_id].to_i
@board_position_id = params[:searchparams][:board_position_id].to_i
@club_position_id = params[:searchparams][:club_position_id].to_i
@only_active = (params[:searchparams][:only_active] == '1')
if params[:searchparams].has_key? :club_id
@club_id = params[:searchparams][:club_id].map{|x| x.to_i}
end
end
end
def conditions
variables = []
conditions = []
conditions << "club_id in (?)"
variables << @club_id
if title_id != -100
conditions << "title_id = ?"
variables << @title_id
end
if board_position_id != -100
conditions << "board_position_id = ?"
variables << @board_position_id
end
if club_position_id != -100
conditions << "club_position_id = ?"
variables << @club_position_id
end
return [ conditions.join(" AND ") ] + variables
end
def filter(students)
matched = students
if grade != -100
matched = matched.select { |s| s.current_grade != nil && s.current_grade.grade_id == @grade }
end
if group_id != -100
matched = matched.select { |s| s.group_ids.include? group_id }
end
if only_active
matched = matched.select { |s| s.active? }
end
return matched
end
def find_all
@students = Student.find(:all, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ], :conditions => conditions, :order => "fname, sname")
@students = filter(@students)
return @students
end
def find_in_club(club)
@students = club.students.find(:all, :include => [ "graduations", "payments", "club", "groups", "main_interest", "board_position", "club_position", "title" ], :conditions => conditions, :order => "fname, sname")
@students = filter(@students)
return @students
end
end
class StudentsController < ApplicationController
before_filter :require_administrator, :except => [ :register, :edit, :update ]
before_filter :require_student_or_administrator, :only => [ :edit, :update ]
def index
@searchparams = SearchParams.new(params)
@club = Club.find(params[:club_id])
@students = @searchparams.find_in_club(@club)
respond_to do |format|
format.html # index.html
format.csv do
if require_export_permission(@club)
send_data(students_csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=#{@club.name}.csv")
return
end
end
end
end
def filter
@searchparams = SearchParams.new(params)
@club = Club.find(params[:club_id])
@students = @searchparams.find_in_club(@club)
end
def search
@searchparams = SearchParams.new(params)
@clubs = Club.find(:all, :order => :name)
@students = @searchparams.find_all
end
def show
@student = Student.find(params[:id])
@club = @student.club
end
def new
@club = Club.find(params[:club_id])
@student = Student.new
@student.club = @club
@student.mailing_lists = MailingList.find_all_by_default_and_club_id(1, nil) + MailingList.find_all_by_default_and_club_id(1, @club.id)
@student.groups = Group.find(:all, :conditions => { :default => 1 })
end
def edit
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
end
def create
@student = Student.new(params[:student])
+
+ # This is an ugly hack that uses the random perishable token as a base password for the user.
+ @student.reset_perishable_token!
+ @student.password = @student.password_confirmation = @student.perishable_token
+ @student.reset_perishable_token!
+
@club = @student.club
if params.key? :member_of
group_ids = params[:member_of].keys
@student.group_ids = group_ids
end
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
end
if @student.save
flash[:notice] = t:Student_created
redirect_to(@student)
else
render :action => "new"
end
end
def update
@student = Student.find(params[:id])
require_administrator_or_self(@student)
@club = @student.club
if current_user.type == 'Administrator' && params.key?(:member_of)
group_ids = params[:member_of].keys
@student.group_ids = group_ids
else
@student.groups.clear
end
# TODO: This is insecure, a student could potentially join a mailing list they shouldn't by editing hidden fields.
if params.key? :subscribes_to
ml_ids = params[:subscribes_to].keys
@student.mailing_list_ids = ml_ids
else
@student.mailing_lists.clear
end
success = @student.update_attributes(params[:student])
if current_user.type == 'Administrator'
flash[:notice] = t(:Student_updated) if success
redirect = student_path(@student)
elsif current_user.type == 'Student'
flash[:notice] = t(:Self_updated) if success
redirect = edit_student_path(@student)
end
if success
redirect_to redirect
else
render :action => "edit"
end
end
def destroy
@student = Student.find(params[:id])
@student.destroy
redirect_to(@student.club)
end
def bulk_operations
session[:before_bulk] = request.referer
session[:selected_students] = params[:selected_students]
operation = "bulk_message" if params[:bulk_message]
operation = "bulk_payments" if params[:bulk_payments]
operation = "bulk_graduations" if params[:bulk_graduations]
if operation == "bulk_graduations"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
if operation == "bulk_payments"
redirect_to :controller => 'graduations', :action => 'new_bulk'
end
end
def register
@student = Student.new
end
private
def students_csv
csv_string = FasterCSV.generate do |csv|
csv << ["id", "first_name", "last_name", "groups", "personal_number", "gender", "main_interest", "email", "mailing_lists", "home_phone", "mobile_phone", "address", "title", "board_position", "club_position", "comments", "grade", "graduated", "payment_recieved", "payment_amount", "payment_description"]
@students.each do |user|
csv << [user.id, user.fname, user.sname, user.groups.map{|g| g.identifier}.join(","), user.personal_number, user.gender, user.main_interest.category, user.email, user.mailing_lists.map{|m| m.email}.join(","), user.home_phone, user.mobile_phone, user.street, user.title.title, user.board_position.position, user.club_position.position, user.comments, user.current_grade.try(:grade).try(:description), user.current_grade.try(:graduated), user.latest_payment.try(:received), user.latest_payment.try(:amount), user.latest_payment.try(:description)]
end
end
return csv_string
end
end
diff --git a/app/models/student.rb b/app/models/student.rb
index d4ee3d0..024fc12 100644
--- a/app/models/student.rb
+++ b/app/models/student.rb
@@ -1,118 +1,124 @@
class Student < User
belongs_to :club
has_and_belongs_to_many :groups, :order => "identifier"
has_and_belongs_to_many :mailing_lists
has_many :payments, :order => "received desc", :dependent => :destroy
has_many :graduations, :order => "graduated desc", :dependent => :destroy
belongs_to :main_interest, :class_name => "GradeCategory"
belongs_to :title
belongs_to :club_position
belongs_to :board_position
validates_presence_of :personal_number, :if => REQUIRE_PERSONAL_NUMBER
validates_uniqueness_of :personal_number, :if => Proc.new { |s| !s.personal_number.blank? && s.personal_number =~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d-\d\d\d\d$/ }
validate :check_personal_number
validates_associated :club
validates_associated :graduations
validates_associated :payments
validates_associated :title
validates_associated :club_position
validates_associated :board_position
validates_format_of :gender, :with => /male|female|unknown/
validates_presence_of :main_interest
validates_presence_of :sname
validates_presence_of :fname
validates_presence_of :club
validates_presence_of :board_position
validates_presence_of :club_position
validates_presence_of :title
+ acts_as_authentic do |c|
+ c.validate_password_field = true
+ c.require_password_confirmation = true
+ c.validates_length_of_login_field_options = { :in => 2..20 }
+ end
+
def luhn
fact = 2
sum = 0
personal_number.sub("-", "").split(//)[2..-1].each do |n|
(n.to_i * fact).to_s.split(//).each { |i| sum += i.to_i }
fact = 3 - fact
end
sum % 10
end
def check_personal_number
if !personal_number.blank?
errors.add(:personal_number, :invalid) if personal_number !~ /^(19[3-9]|20[0-2])\d[01]\d[0-3]\d(-\d\d\d\d)?$/
if personal_number.length == 13:
errors.add(:personal_number, :incorrect_check_digit) if luhn != 0
end
end
end
def personal_number=(value)
value = $1 + "-" + $2 if value =~ /^(\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(19\d\d\d\d\d\d)(\d\d\d\d)$/;
value = $1 + "-" + $2 if value =~ /^(20\d\d\d\d\d\d)(\d\d\d\d)$/;
value = "19" + value if value =~ /^[3-9]\d\d\d\d\d(-\d\d\d\d)?$/;
value = "20" + value if value =~ /^[0-2]\d\d\d\d\d(-\d\d\d\d)?$/;
self[:personal_number] = value
end
def name
return fname + " " + sname
end
def login
"student-%d" % id
end
def latest_payment
if !payments.blank?
return payments[0]
else
p = Payment.new
p.amount = 0
p.received = created_at
p.description = "Start"
return p
end
end
def current_grade
if graduations.blank?
return nil
else
in_main_interest = graduations.select { |g| g.grade_category == main_interest }
if in_main_interest.length > 0
return in_main_interest[0]
else
return graduations[0]
end
end
end
def active?
if payments.blank?
return Time.now - created_at < 86400 * 45
else
return Time.now - payments[0].received < 86400 * 180
end
end
def gender
if personal_number =~ /-\d\d(\d)\d$/
return $1.to_i.even? ? 'female' : 'male'
end
return self[:gender] unless self[:gender].blank?
return 'unknown'
end
def age
if personal_number =~ /^(\d\d\d\d)(\d\d)(\d\d)/
d = Date.new($1.to_i, $2.to_i, $3.to_i)
return ((Date.today-d) / 365.24).to_i
else
return -1
end
end
def group_list
groups.map{ |g| g.identifier }.join(", ")
end
end
diff --git a/app/views/students/_form.html.erb b/app/views/students/_form.html.erb
index 51d9fae..a065d3b 100644
--- a/app/views/students/_form.html.erb
+++ b/app/views/students/_form.html.erb
@@ -1,116 +1,121 @@
<%= f.hidden_field :club_id, :class => 'text_field' %>
<div class="group">
<%= f.label :fname, t(:Groups), :class => :label %>
<% groups.each do |group| -%>
<label>
<%= check_box_tag "member_of[" + group.id.to_s + "]", value = "1", checked = @student.group_ids.include?(group.id) %>
<%=group.identifier%>
</label><br/>
<% end -%>
</div>
<div class="group">
<%= f.label :fname, t(:Fname), :class => :label %>
<%= f.text_field :fname, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :sname, t(:Sname), :class => :label %>
<%= f.text_field :sname, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :personal_number, t(:Personal_Num), :class => :label %>
<%= f.text_field :personal_number, :class => 'text_field' %>
<span class="description"><%=t :Personal_Num_descr%></span>
</div>
<div class="group">
<%= f.label :gender, t(:Gender), :class => :label %>
<%= select "student", "gender", ['male', 'female', 'unknown'].map { |g| [ t(g).titlecase, g ] } %><br/>
<span class="description"><%=t:Gender_descr%></span>
</div>
<div class="group">
<%= f.label :main_interest_id, t(:Main_Interest), :class => :label %>
<%= select "student", "main_interest_id", grade_categories.map { |g| [ g.category, g.id ] } %><br/>
</div>
<div class="group">
<%= f.label :email, t(:Email), :class => :label %>
<%= f.text_field :email, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :mailing_lists, t(:Mailing_Lists), :class => :label %>
<% mailing_lists.each do |ml| -%>
<% if ml.club == nil || ml.club == @club -%>
<label><td><%= check_box_tag "subscribes_to[" + ml.id.to_s + "]", value = "1", checked = @student.mailing_list_ids.include?(ml.id) %> <%=ml.description%></label><br/>
<% end -%>
<% end -%>
</table>
</div>
<div class="group">
<%= f.label :home_phone, t(:Home_phone), :class => :label %>
<%= f.text_field :home_phone, :class => 'text_field' %>
<span class="description"><%=t :Phone_number_descr%></span>
</div>
<div class="group">
<%= f.label :mobile_phone, t(:Mobile_phone), :class => :label %>
<%= f.text_field :mobile_phone, :class => 'text_field' %>
<span class="description"><%=t :Phone_number_descr%></span>
</div>
<div class="group">
<%= f.label :street, t(:Street), :class => :label %>
<%= f.text_field :street, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :zipcode, t(:Zipcode), :class => :label %>
<%= f.text_field :zipcode, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :city, t(:City), :class => :label %>
<%= f.text_field :city, :class => 'text_field' %>
</div>
<div class="group">
<%= f.label :title_id, t(:Title), :class => :label %>
<%= select "student", "title_id", titles.map { |g| [ g.title, g.id ] } %><br/>
</div>
<div class="group">
<%= f.label :club_position_id, t(:Club_Position), :class => :label %>
<%= select "student", "club_position_id", club_positions.map { |g| [ g.position, g.id ] } %><br/>
</div>
<div class="group">
<%= f.label :board_position_id, t(:Board_Position), :class => :label %>
<%= select "student", "board_position_id", board_positions.map { |g| [ g.position, g.id ] } %><br/>
</div>
<div class="group">
<%= f.label :comments, t(:Comments), :class => :label %>
<%= f.text_area :comments, :class => 'text_area', :rows => 4, :cols => 16 %>
</div>
<div class="group">
<%= f.label :password, t(:New_Password), :class => :label %>
- <%= f.text_field :password, :class => 'text_field' %>
+ <%= f.password_field :password, :class => 'text_field' %>
<span class="description"><%=t :New_Password_descr%></span>
</div>
+<div class="group">
+ <%= f.label :password_confirmation, t(:Confirm_Password), :class => :label %>
+ <%= f.password_field :password_confirmation, :class => 'text_field' %>
+</div>
+
<div class="group navform">
<input type="submit" class="button" value="<%=t :Save%> →" />
<% if controller.action_name != "new" && controller.action_name != "create" %>
<% if current_user.delete_permission?(@club) %>
<%=t(:or)%> <%= link_to t(:Destroy), @student, :confirm => t(:Are_you_sure_student), :method => :delete %>
<% end %>
<%=t :or%> <%= link_to t(:Cancel), student_path(@student) %>
<% end %>
</div>
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 2e1fe20..ec5b2d6 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,270 +1,270 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
Reset_password: Ã
terställ lösenord
- Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord has skickats med epost. Vänligen kontrollera din epost.
+ Mailed_reset_instruction: Instruktioner för att återställa ditt lösenord har skickats med epost. Vänligen kontrollera din epost.
No_user_found: Ingen användare kunde hittas med den epostadressen eller kontonamnet.
Password_updated: Lösenordet har uppdaterats.
Could_not_load_account: Vi kunde inte hitta ditt konto. Testa att kopiera URL:en från mailet direkt till din webbläsare och försök igen.
Password_reset_descr: Ange ditt kontonamn (som administratatör) eller epostadress.
Request_password_reset: Ã
terställ lösenord
Forgot_password: Glömt ditt lösenord?
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
- login: användarnamn
- email: epostadress
- password: lösenord
- remember_me: kom ihåg mig
+ login: Användarnamn
+ email: Epostadress
+ password: Lösenord
+ remember_me: Kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
confirmation: stämmer inte med konfirmationen
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
diff --git a/test/fixtures/payments.yml b/test/fixtures/payments.yml
index 13b9df3..db3c063 100644
--- a/test/fixtures/payments.yml
+++ b/test/fixtures/payments.yml
@@ -1,49 +1,36 @@
----
payments_001:
student_id: "30"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "100.0"
id: "225070851"
received: <%= 14.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift VT2009"
payments_002:
student_id: "30"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "500.0"
id: "319740578"
received: <%= 14.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift VT2009"
payments_003:
student_id: "29"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "100.0"
id: "980190962"
received: <%= 14.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift VT2009"
payments_004:
student_id: "31"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "50.0"
id: "980254618"
- received: <%= 4.months.ago.to_s(:db) %>
+ received: <%= 14.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift HT2009"
payments_005:
student_id: "135"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "2.0"
id: "1005520445"
received: <%= 4.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift HT2009"
payments_006:
student_id: "94"
- created_at: 2009-12-09 09:09:19
- updated_at: 2009-12-09 09:09:19
amount: "700.0"
id: "1025039570"
received: <%= 4.months.ago.to_s(:db) %>
description: "Tr\xC3\xA4ningsavgift HT2009"
diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml
index 0230719..2ec1ab6 100644
--- a/test/fixtures/users.yml
+++ b/test/fixtures/users.yml
@@ -1,571 +1,570 @@
----
-users_015:
+users_015:
city: "Vall\xC3\xA5kra"
single_access_token: zDafGGhEtEtfK9g11eZx
- last_request_at:
+ last_request_at:
personal_number: 19850107-1768
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: OS2yY7jSgwHnI0HmUvBv
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "26030"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "3"
board_position_id: "1"
id: "614887029"
- current_login_ip:
+ current_login_ip:
street: "Mj\xC3\xB6lkal\xC3\xA5nga 64"
home_phone: 042-3409841
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 181ce34df4e5704fb47f07dd41209df8840903c9e2e0d1595b0e1b37086d4771d19678af672a68b442f5d1ea85c4492618e346c09ea2566dc25d2864494b2669
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Marielle
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Dahlberg
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_004:
+users_004:
city: Arvidsjaur
single_access_token: pLUnSxRXdioKC6DrVs48
- last_request_at:
+ last_request_at:
personal_number: 19710730-3187
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: qLIqIc9Eulplp2gVOV2Q
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "93000"
main_interest_id: "2"
- groups_permission:
+ groups_permission:
club_id: "2"
board_position_id: "1"
id: "27"
- current_login_ip:
+ current_login_ip:
street: Barrgatan 81
home_phone: 0960-8472971
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 26db96d89f9b07cb86e3980ddbcf3382b668e8537ef9ab90f6a9a5430840ce406ea4c161a6f43fe7e4142e9944f63586242896367e10b3ea4079386571f5852d
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Emma
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Petterson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_005:
+users_005:
city: "Svart\xC3\xA5"
single_access_token: WLpBRwcuouV2JocfhNXd
- last_request_at:
+ last_request_at:
personal_number: 19420814-3778
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: fIDpa7BWiLZXoPeJxFdT
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "69330"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "3"
board_position_id: "1"
id: "29"
- current_login_ip:
+ current_login_ip:
street: "Verdandi Gr\xC3\xA4nd 65"
home_phone: ""
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 85f36153d06ac5c77e31f88655341bcad50ea360a1680d5b883f5ddecb9e64c6c1da1258f4b0c631df11900956698d49848ec6de0398714ef1eabaa0bca98217
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Emil
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: "Nystr\xC3\xB6m"
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_006:
- city:
+users_006:
+ city:
single_access_token: PukZmC0UFMPgAS6XOieY
- last_request_at:
- personal_number:
- created_at: 2009-12-13 21:05:43
- comments:
+ last_request_at:
+ personal_number:
+ created_at: <%= 14.months.ago.to_s(:db) %>
+ comments:
crypted_password: 9bad0e92a8e4e713700495c3e058cd1c0781396b3ef7ae3a6d06eceaca5f634b
perishable_token: OiANbF63ZoKpxPUuZGbs
- updated_at: 2009-12-13 21:06:02
- zipcode:
- main_interest_id:
+ updated_at: <%= 14.months.ago.to_s(:db) %>
+ zipcode:
+ main_interest_id:
groups_permission: "0"
- club_id:
- board_position_id:
+ club_id:
+ board_position_id:
id: "30"
- current_login_ip:
- street:
- home_phone:
- gender:
- failed_login_count:
+ current_login_ip:
+ street:
+ home_phone:
+ gender:
+ failed_login_count:
type: Administrator
- title_id:
- current_login_at:
- login_count:
+ title_id:
+ current_login_at:
+ login_count:
persistence_token: e12a68f9f736ea810817e7b5822130e187a239a78715820ec21003489f748c83965bb48e0fef5eefb2f7de6cb4faa380487c808442d6cb05d8cb2a6721257086
users_permission: "0"
mailinglists_permission: "0"
fname: Chief
- last_login_ip:
+ last_login_ip:
site_permission: "0"
- last_login_at:
+ last_login_at:
login: ci
sname: Instructor
clubs_permission: "0"
email: [email protected]
- club_position_id:
- mobile_phone:
-users_007:
+ club_position_id:
+ mobile_phone:
+users_007:
city: Kristianstad
single_access_token: G2-Mx5dZZv1Sztom3ESU
- last_request_at:
+ last_request_at:
personal_number: 19460723-4780
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: kIAInJyDT5aTVEy8J5pc
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "12353"
main_interest_id: "3"
- groups_permission:
+ groups_permission:
club_id: "4"
board_position_id: "1"
id: "31"
- current_login_ip:
+ current_login_ip:
street: "Norra B\xC3\xA4ckebo 5"
home_phone: 044-212936
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 87527942b789db8c88d2a9f81c263e951d7134a01419cb5f67904b679d65200c38009fcbac11e239472d45fdbff3c94d89c30fb2e64650948042dc2d875a307c
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Elif
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Johnsson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_008:
+users_008:
city: "Frilles\xC3\xA5s"
single_access_token: AbZ6siLotedB55t3a0N6
- last_request_at:
+ last_request_at:
personal_number: 19810628-1861
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: V4O3hMrdtyH6Raegbp1K
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "43030"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "4"
board_position_id: "1"
id: "32"
- current_login_ip:
+ current_login_ip:
street: "Tuvv\xC3\xA4gen 20"
home_phone: ""
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 1b9fc09c5f843dc0d05ad9f767aab9e53e05af07954cd0538896cc70aa417ff49f91251a84fb254667e521aebf1cb97d52843ee8c22265a0c401d665b9dfc9b1
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Lisen
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Berggren
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_010:
+users_010:
city: Tandsbyn
single_access_token: 4f0mzVSsGtutT4lR788A
- last_request_at:
+ last_request_at:
personal_number: 19671029-1219
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: 2tzua9jnq8Ieyg1C7YIW
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "83021"
main_interest_id: "2"
- groups_permission:
+ groups_permission:
club_id: "5"
board_position_id: "1"
id: "35"
- current_login_ip:
+ current_login_ip:
street: Stallstigen 47
home_phone: 063-5312134
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: c8dd0a057199cb3386c2da4ab9fa84cbdcd3a70058685626d06ee551a000990e6c1e5d65b1bffa50a384046787d706594ff1cee76153025569e71c3b097a5f17
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Nino
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Berg
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_009:
+users_009:
city: Kvicksund
single_access_token: QBIZWu_swyIvbvjgzAcn
- last_request_at:
+ last_request_at:
personal_number: 19581214-1496
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: Hl0KIzquCA5fmMoHMs6n
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "64045"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "4"
board_position_id: "1"
id: "34"
- current_login_ip:
+ current_login_ip:
street: "Kl\xC3\xA4ppinge 89"
home_phone: 0563-9198417
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: ad3ce523fcc6b40f2593c5c8b980aec9e530a749d1895f51a5368070dda1991f0078ae045ca369fa12f16d544edfcedd4e5c3252a3855a264b9eccef800b3f7f
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Edgar
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Holmberg
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_011:
+users_011:
city: "F\xC3\xA5gelfors"
single_access_token: LGOQfxGdt4YOrU5asK6O
- last_request_at:
+ last_request_at:
personal_number: 19670425-7176
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: 8-LO-mmC6NRCr-M8tLvF
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "57075"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "5"
board_position_id: "1"
id: "36"
- current_login_ip:
+ current_login_ip:
street: ""
home_phone: 0491-5675992
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 629d78c925e23604c16d10df964fad2e83b433b69125f9feff45f6bb3254361d6c713aba6b5e8f9d638e2422e327ecb953e5ed4a8e69f8a3ae9de39ce71043f0
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Devin
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Johansson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_012:
+users_012:
city: Ljungby
single_access_token: r3-xfoMODusX9u53yZkX
- last_request_at:
+ last_request_at:
personal_number: 19510709-8054
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: 4fYpUiPrU70vlo86swvz
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "34147"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "8"
board_position_id: "1"
id: "135"
- current_login_ip:
+ current_login_ip:
street: Bygget 73
home_phone: 0372-9283685
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: cfba9b4d6ed63659b98a6326f749809ad648d59d515f98977ffe4bc0e3dca4337bfebf2069c2b89db5ac731c909ce4da1ea53fcd5e5d59782928c8f990f5f394
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Razmus
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Hermansson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_001:
- city:
+users_001:
+ city:
single_access_token: RcNDgaUdOCKapN7hWLUU
last_request_at: 2010-01-26 18:20:16
- personal_number:
- created_at: 2009-12-09 09:09:19
- comments:
+ personal_number:
+ created_at: <%= 14.months.ago.to_s(:db) %>
+ comments:
crypted_password: 6694a5cda8fcb5ddcfd6171ce35de9e593c20da32b0341917f4f1f6d40ce6d98
perishable_token: CLSbAu-0HlViX9BHA15J
- updated_at: 2010-01-26 18:20:16
- zipcode:
- main_interest_id:
+ updated_at: <%= 14.months.ago.to_s(:db) %>
+ zipcode:
+ main_interest_id:
groups_permission: "1"
- club_id:
- board_position_id:
+ club_id:
+ board_position_id:
id: "1"
current_login_ip: 127.0.0.1
- street:
- home_phone:
- gender:
+ street:
+ home_phone:
+ gender:
failed_login_count: "0"
type: Administrator
- title_id:
+ title_id:
current_login_at: 2010-01-26 18:20:07
login_count: "16"
persistence_token: 0f1dae1907c73885dcbeab9af3105ddf202a6aa8e2dc3ea93b2178a734e183b946a3c5ecfc4bbd7634344dbf7aec7070a4f5976a848ea38ec9d64a31d27c489a
users_permission: "1"
mailinglists_permission: "1"
fname: Admin
last_login_ip: 127.0.0.1
site_permission: "1"
last_login_at: 2010-01-26 18:15:07
login: admin
sname: Istrator
clubs_permission: "1"
email: [email protected]
- club_position_id:
- mobile_phone:
-users_013:
+ club_position_id:
+ mobile_phone:
+users_013:
city: Edsvalla
single_access_token: LaRu89LjhsoSjbl5oUW2
- last_request_at:
+ last_request_at:
personal_number: 19500513-8515
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: xHgKK1uasoMGO2Dt_E1C
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "66052"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "8"
board_position_id: "1"
id: "136"
- current_login_ip:
+ current_login_ip:
street: ""
home_phone: 054-7334012
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 301e09c1198d69f3d609a517d58ac3c1a0f84d15c698627acaba710292eb7c574bae66d99a0cb12f236e4bdf3b8ff998c119d9d2e24a821729a8f074e8d26f73
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Baran
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Olofsson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_002:
+users_002:
city: "Br\xC3\xA5landa"
single_access_token: 1Is4aPKS401krBlSDD7Z
- last_request_at:
+ last_request_at:
personal_number: 19810203-9909
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: r-Wjwf1Dbtqe5oSEQKt-
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "46065"
main_interest_id: "3"
- groups_permission:
+ groups_permission:
club_id: "2"
board_position_id: "1"
id: "25"
- current_login_ip:
+ current_login_ip:
street: Valldammsgatan 42
home_phone: 0521-9520867
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: f464267a0b07fda46e6ebc1e42e5a7f4ddba7992c230a814ca2d3f5cae79541f0da9f61c21195a94c195e38f3eccf7bd056263999047e3a04566040308d259c3
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Amalia
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Gustavsson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_014:
+users_014:
city: Nybro
single_access_token: mFlg5QnvGvSij7hU7TpA
- last_request_at:
+ last_request_at:
personal_number: 19450326-9377
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 14.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: Bc-8EaOIqSYd1d4TJ1mH
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 14.months.ago.to_s(:db) %>
zipcode: "0"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "9"
board_position_id: "1"
id: "137"
- current_login_ip:
+ current_login_ip:
street: Valldammsgatan 42
home_phone: 0481-5635981
gender: male
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: bd184489c816e9713f0e7a80b877e1566c2069b92ecce03cce7ca08c6418c80ee1921eb3bcec1e49da2440a55f9cd919d8d0f7b13482bb7e1aa734c7014b1f93
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Svante
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Jansson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
-users_003:
+users_003:
city: "F\xC3\x96LLINGE"
single_access_token: wZH5gvpBWujlA_Vmvhka
- last_request_at:
+ last_request_at:
personal_number: 19620629-3349
- created_at: 2009-12-09 09:09:19
+ created_at: <%= 1.months.ago.to_s(:db) %>
comments: ""
crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
perishable_token: rpa8hlTBpAhcuftX8lC6
- updated_at: 2010-01-26 18:21:35
+ updated_at: <%= 1.months.ago.to_s(:db) %>
zipcode: "83066"
main_interest_id: "1"
- groups_permission:
+ groups_permission:
club_id: "2"
board_position_id: "1"
id: "26"
- current_login_ip:
+ current_login_ip:
street: "Norrfj\xC3\xA4ll 44"
home_phone: 0645-7595472
gender: female
- failed_login_count:
+ failed_login_count:
type: Student
title_id: "1"
- current_login_at:
- login_count:
+ current_login_at:
+ login_count:
persistence_token: 508d9227ac884460493a5a07a66af16dd5a363fa116bf421a824c1f9f911e92090bb212728fa05d5c26bf4fb6a207261ec11a86256093f2888ead23d78165f46
- users_permission:
- mailinglists_permission:
+ users_permission:
+ mailinglists_permission:
fname: Agaton
- last_login_ip:
- site_permission:
- last_login_at:
- login:
+ last_login_ip:
+ site_permission:
+ last_login_at:
+ login:
sname: Johnsson
- clubs_permission:
+ clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
diff --git a/test/integration/reset_password_test.rb b/test/integration/reset_password_test.rb
new file mode 100644
index 0000000..77a89d1
--- /dev/null
+++ b/test/integration/reset_password_test.rb
@@ -0,0 +1,49 @@
+require 'test_helper'
+
+class ResetPasswordTest < ActionController::IntegrationTest
+ fixtures :all
+
+ test "verify redirect when logged in" do
+ log_in
+
+ visit "/password_resets/new"
+ assert_contain "Användarprofil"
+ assert_contain "Admin Istrator"
+ end
+
+ test "verify reset with admin username" do
+ visit "/password_resets/new"
+ fill_in "Användarnamn eller epostadress", :with => "admin"
+ click_button "Ã
terställ lösenord"
+ assert_contain "har skickats"
+ end
+
+ test "verify reset with user email" do
+ visit "/password_resets/new"
+ fill_in "Användarnamn eller epostadress", :with => "[email protected]"
+ click_button "Ã
terställ lösenord"
+ assert_contain "har skickats"
+ end
+
+ test "verify setting new password for admin" do
+ a = User.find_by_login("admin")
+ a.reset_perishable_token!
+ pt = a.perishable_token
+ visit "/password_resets/#{pt}/edit"
+ fill_in "Lösenord", :with => "password"
+ fill_in "Upprepa lösenordet", :with => "password"
+ click_button "Ã
terställ lösenord"
+ assert_contain "har uppdaterats"
+ end
+
+ test "verify setting new password for user" do
+ a = User.find_by_email("[email protected]")
+ a.reset_perishable_token!
+ pt = a.perishable_token
+ visit "/password_resets/#{pt}/edit"
+ fill_in "Lösenord", :with => "password"
+ fill_in "Upprepa lösenordet", :with => "password"
+ click_button "Ã
terställ lösenord"
+ assert_contain "har uppdaterats"
+ end
+end
diff --git a/test/integration/users_test.rb b/test/integration/users_test.rb
index 8abc055..a824146 100644
--- a/test/integration/users_test.rb
+++ b/test/integration/users_test.rb
@@ -1,28 +1,37 @@
require 'test_helper'
class UsersTest < ActionController::IntegrationTest
fixtures :all
test "check groups" do
log_in
click_link "Användare"
click_link "Ny användare"
fill_in "Användarnamn", :with => "test"
fill_in "Förnamn", :with => "Test"
fill_in "Efternamn", :with => "Testsson"
fill_in "Epostadress", :with => "[email protected]"
fill_in "Lösenord", :with => "abc123"
fill_in "Upprepa lösenordet", :with => "abc123"
check "permission[8][read]"
click_button "Spara"
assert_contain "har skapats"
assert_contain "Test Testsson"
click_link "test"
assert_contain /Edsvalla:\s+Se[^,]/m
assert_not_contain "Brålanda"
assert_not_contain "Nybro"
end
+
+ test "log in as student" do
+ visit "/"
+ fill_in "Användarnamn eller epostadress", :with => "[email protected]"
+ fill_in "Lösenord", :with => "password"
+ click_button "Logga in"
+ assert_contain "Epostadress"
+ assert_contain "Epostlistor"
+ end
end
diff --git a/test/unit/student_test.rb b/test/unit/student_test.rb
index c6e63b6..2ffe6d1 100644
--- a/test/unit/student_test.rb
+++ b/test/unit/student_test.rb
@@ -1,63 +1,65 @@
require 'test_helper'
class StudentTest < ActiveSupport::TestCase
test "luhn calculation" do
s = Student.new
s.personal_number = "198002020710"
assert s.luhn == 0
s.personal_number = "197501230580"
assert s.luhn == 0
end
test "validations" do
s = Student.new
s.sname = "Johansson"
s.fname = "Karon"
s.email = "[email protected]"
s.home_phone = "0410-6495551"
s.mobile_phone = ""
s.street = "Bonaröd 78"
s.zipcode = "23021"
s.city = "Beddingestrand"
s.title_id = 1
s.club_position_id = 1
s.board_position_id = 1
s.comments = "None"
s.main_interest_id = 1
s.club_id = 9
+ s.password = "password"
+ s.password_confirmation = "password"
s.personal_number = nil
assert !s.save # Nil personal number
s.personal_number = "19710730-3187"
assert !s.save # Duplicate personal number
s.personal_number = "abc123"
assert !s.save # Nonsense personal number
s.personal_number = ""
assert !s.save # Blank personal number
s.personal_number = "20710730-3187"
assert !s.save # Invalid personal number
s.personal_number = "710730-3187"
assert !s.save # Invalid personal number format
s.personal_number = "7107303187"
assert !s.save # Invalid personal number format
s.personal_number = "197107303187"
assert !s.save # Invalid personal number format
s.personal_number = "19550213-2490"
assert s.save # Valid personal number
s.personal_number = "19710730"
assert s.save # Valid birth date
s.personal_number = "abc123"
assert s.personal_number == "abc123"
s.personal_number = "20710730-3187"
assert s.personal_number == "20710730-3187"
s.personal_number = "7107303187"
assert s.personal_number == "19710730-3187"
s.personal_number = "710730-3187"
assert s.personal_number == "19710730-3187"
s.personal_number = "197107303187"
assert s.personal_number == "19710730-3187"
s.personal_number = "19710730-3187"
assert s.personal_number == "19710730-3187"
end
end
|
calmh/Register
|
d5b0f93821e1d088e4180073dfaecf3354cc847a
|
Have valid tokens in fixtures
|
diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml
index 5de29e3..0230719 100644
--- a/test/fixtures/users.yml
+++ b/test/fixtures/users.yml
@@ -1,571 +1,571 @@
---
users_015:
city: "Vall\xC3\xA5kra"
single_access_token: zDafGGhEtEtfK9g11eZx
last_request_at:
personal_number: 19850107-1768
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token: 5rQ0RBAYZmO754GLDgTx
- updated_at: 2009-12-21 09:14:05
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: OS2yY7jSgwHnI0HmUvBv
+ updated_at: 2010-01-26 18:21:35
zipcode: "26030"
main_interest_id: "1"
groups_permission:
club_id: "3"
board_position_id: "1"
id: "614887029"
current_login_ip:
street: "Mj\xC3\xB6lkal\xC3\xA5nga 64"
home_phone: 042-3409841
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token: 187d92abdfe267759a5574b8e1cbc7569bbad127be89e15922077c5f174ca28ebf0dc4b2d0fd573558a7b2bd92edee677fc210a005a6fff3f45dc5734327b38a
+ persistence_token: 181ce34df4e5704fb47f07dd41209df8840903c9e2e0d1595b0e1b37086d4771d19678af672a68b442f5d1ea85c4492618e346c09ea2566dc25d2864494b2669
users_permission:
mailinglists_permission:
fname: Marielle
last_login_ip:
site_permission:
last_login_at:
login:
sname: Dahlberg
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_004:
city: Arvidsjaur
- single_access_token:
+ single_access_token: pLUnSxRXdioKC6DrVs48
last_request_at:
personal_number: 19710730-3187
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:27:19
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: qLIqIc9Eulplp2gVOV2Q
+ updated_at: 2010-01-26 18:21:35
zipcode: "93000"
main_interest_id: "2"
groups_permission:
club_id: "2"
board_position_id: "1"
id: "27"
current_login_ip:
street: Barrgatan 81
home_phone: 0960-8472971
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 26db96d89f9b07cb86e3980ddbcf3382b668e8537ef9ab90f6a9a5430840ce406ea4c161a6f43fe7e4142e9944f63586242896367e10b3ea4079386571f5852d
users_permission:
mailinglists_permission:
fname: Emma
last_login_ip:
site_permission:
last_login_at:
login:
sname: Petterson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_005:
city: "Svart\xC3\xA5"
- single_access_token:
+ single_access_token: WLpBRwcuouV2JocfhNXd
last_request_at:
personal_number: 19420814-3778
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:27:25
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: fIDpa7BWiLZXoPeJxFdT
+ updated_at: 2010-01-26 18:21:35
zipcode: "69330"
main_interest_id: "1"
groups_permission:
club_id: "3"
board_position_id: "1"
id: "29"
current_login_ip:
street: "Verdandi Gr\xC3\xA4nd 65"
home_phone: ""
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 85f36153d06ac5c77e31f88655341bcad50ea360a1680d5b883f5ddecb9e64c6c1da1258f4b0c631df11900956698d49848ec6de0398714ef1eabaa0bca98217
users_permission:
mailinglists_permission:
fname: Emil
last_login_ip:
site_permission:
last_login_at:
login:
sname: "Nystr\xC3\xB6m"
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_006:
city:
single_access_token: PukZmC0UFMPgAS6XOieY
last_request_at:
personal_number:
created_at: 2009-12-13 21:05:43
comments:
crypted_password: 9bad0e92a8e4e713700495c3e058cd1c0781396b3ef7ae3a6d06eceaca5f634b
perishable_token: OiANbF63ZoKpxPUuZGbs
updated_at: 2009-12-13 21:06:02
zipcode:
main_interest_id:
groups_permission: "0"
club_id:
board_position_id:
id: "30"
current_login_ip:
street:
home_phone:
gender:
failed_login_count:
type: Administrator
title_id:
current_login_at:
login_count:
persistence_token: e12a68f9f736ea810817e7b5822130e187a239a78715820ec21003489f748c83965bb48e0fef5eefb2f7de6cb4faa380487c808442d6cb05d8cb2a6721257086
users_permission: "0"
mailinglists_permission: "0"
fname: Chief
last_login_ip:
site_permission: "0"
last_login_at:
login: ci
sname: Instructor
clubs_permission: "0"
email: [email protected]
club_position_id:
mobile_phone:
users_007:
city: Kristianstad
- single_access_token:
+ single_access_token: G2-Mx5dZZv1Sztom3ESU
last_request_at:
personal_number: 19460723-4780
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:27:35
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: kIAInJyDT5aTVEy8J5pc
+ updated_at: 2010-01-26 18:21:35
zipcode: "12353"
main_interest_id: "3"
groups_permission:
club_id: "4"
board_position_id: "1"
id: "31"
current_login_ip:
street: "Norra B\xC3\xA4ckebo 5"
home_phone: 044-212936
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 87527942b789db8c88d2a9f81c263e951d7134a01419cb5f67904b679d65200c38009fcbac11e239472d45fdbff3c94d89c30fb2e64650948042dc2d875a307c
users_permission:
mailinglists_permission:
fname: Elif
last_login_ip:
site_permission:
last_login_at:
login:
sname: Johnsson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_008:
city: "Frilles\xC3\xA5s"
- single_access_token:
+ single_access_token: AbZ6siLotedB55t3a0N6
last_request_at:
personal_number: 19810628-1861
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:27:55
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: V4O3hMrdtyH6Raegbp1K
+ updated_at: 2010-01-26 18:21:35
zipcode: "43030"
main_interest_id: "1"
groups_permission:
club_id: "4"
board_position_id: "1"
id: "32"
current_login_ip:
street: "Tuvv\xC3\xA4gen 20"
home_phone: ""
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 1b9fc09c5f843dc0d05ad9f767aab9e53e05af07954cd0538896cc70aa417ff49f91251a84fb254667e521aebf1cb97d52843ee8c22265a0c401d665b9dfc9b1
users_permission:
mailinglists_permission:
fname: Lisen
last_login_ip:
site_permission:
last_login_at:
login:
sname: Berggren
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_010:
city: Tandsbyn
- single_access_token:
+ single_access_token: 4f0mzVSsGtutT4lR788A
last_request_at:
personal_number: 19671029-1219
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:28:02
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: 2tzua9jnq8Ieyg1C7YIW
+ updated_at: 2010-01-26 18:21:35
zipcode: "83021"
main_interest_id: "2"
groups_permission:
club_id: "5"
board_position_id: "1"
id: "35"
current_login_ip:
street: Stallstigen 47
home_phone: 063-5312134
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: c8dd0a057199cb3386c2da4ab9fa84cbdcd3a70058685626d06ee551a000990e6c1e5d65b1bffa50a384046787d706594ff1cee76153025569e71c3b097a5f17
users_permission:
mailinglists_permission:
fname: Nino
last_login_ip:
site_permission:
last_login_at:
login:
sname: Berg
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_009:
city: Kvicksund
- single_access_token:
+ single_access_token: QBIZWu_swyIvbvjgzAcn
last_request_at:
personal_number: 19581214-1496
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:29:01
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: Hl0KIzquCA5fmMoHMs6n
+ updated_at: 2010-01-26 18:21:35
zipcode: "64045"
main_interest_id: "1"
groups_permission:
club_id: "4"
board_position_id: "1"
id: "34"
current_login_ip:
street: "Kl\xC3\xA4ppinge 89"
home_phone: 0563-9198417
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: ad3ce523fcc6b40f2593c5c8b980aec9e530a749d1895f51a5368070dda1991f0078ae045ca369fa12f16d544edfcedd4e5c3252a3855a264b9eccef800b3f7f
users_permission:
mailinglists_permission:
fname: Edgar
last_login_ip:
site_permission:
last_login_at:
login:
sname: Holmberg
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_011:
city: "F\xC3\xA5gelfors"
- single_access_token:
+ single_access_token: LGOQfxGdt4YOrU5asK6O
last_request_at:
personal_number: 19670425-7176
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:28:10
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: 8-LO-mmC6NRCr-M8tLvF
+ updated_at: 2010-01-26 18:21:35
zipcode: "57075"
main_interest_id: "1"
groups_permission:
club_id: "5"
board_position_id: "1"
id: "36"
current_login_ip:
street: ""
home_phone: 0491-5675992
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 629d78c925e23604c16d10df964fad2e83b433b69125f9feff45f6bb3254361d6c713aba6b5e8f9d638e2422e327ecb953e5ed4a8e69f8a3ae9de39ce71043f0
users_permission:
mailinglists_permission:
fname: Devin
last_login_ip:
site_permission:
last_login_at:
login:
sname: Johansson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_012:
city: Ljungby
- single_access_token:
+ single_access_token: r3-xfoMODusX9u53yZkX
last_request_at:
personal_number: 19510709-8054
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:28:18
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: 4fYpUiPrU70vlo86swvz
+ updated_at: 2010-01-26 18:21:35
zipcode: "34147"
main_interest_id: "1"
groups_permission:
club_id: "8"
board_position_id: "1"
id: "135"
current_login_ip:
street: Bygget 73
home_phone: 0372-9283685
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: cfba9b4d6ed63659b98a6326f749809ad648d59d515f98977ffe4bc0e3dca4337bfebf2069c2b89db5ac731c909ce4da1ea53fcd5e5d59782928c8f990f5f394
users_permission:
mailinglists_permission:
fname: Razmus
last_login_ip:
site_permission:
last_login_at:
login:
sname: Hermansson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_001:
city:
single_access_token: RcNDgaUdOCKapN7hWLUU
- last_request_at: 2009-12-21 09:14:10
+ last_request_at: 2010-01-26 18:20:16
personal_number:
created_at: 2009-12-09 09:09:19
comments:
crypted_password: 6694a5cda8fcb5ddcfd6171ce35de9e593c20da32b0341917f4f1f6d40ce6d98
- perishable_token: DeIhNFg9cbmfcVvGSchl
- updated_at: 2009-12-21 09:14:10
+ perishable_token: CLSbAu-0HlViX9BHA15J
+ updated_at: 2010-01-26 18:20:16
zipcode:
main_interest_id:
groups_permission: "1"
club_id:
board_position_id:
id: "1"
current_login_ip: 127.0.0.1
street:
home_phone:
gender:
failed_login_count: "0"
type: Administrator
title_id:
- current_login_at: 2009-12-15 09:39:30
- login_count: "10"
+ current_login_at: 2010-01-26 18:20:07
+ login_count: "16"
persistence_token: 0f1dae1907c73885dcbeab9af3105ddf202a6aa8e2dc3ea93b2178a734e183b946a3c5ecfc4bbd7634344dbf7aec7070a4f5976a848ea38ec9d64a31d27c489a
users_permission: "1"
mailinglists_permission: "1"
fname: Admin
- last_login_ip: 194.126.249.11
+ last_login_ip: 127.0.0.1
site_permission: "1"
- last_login_at: 2009-12-13 22:11:25
+ last_login_at: 2010-01-26 18:15:07
login: admin
sname: Istrator
clubs_permission: "1"
email: [email protected]
club_position_id:
mobile_phone:
users_013:
city: Edsvalla
- single_access_token:
+ single_access_token: LaRu89LjhsoSjbl5oUW2
last_request_at:
personal_number: 19500513-8515
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:28:31
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: xHgKK1uasoMGO2Dt_E1C
+ updated_at: 2010-01-26 18:21:35
zipcode: "66052"
main_interest_id: "1"
groups_permission:
club_id: "8"
board_position_id: "1"
id: "136"
current_login_ip:
street: ""
home_phone: 054-7334012
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 301e09c1198d69f3d609a517d58ac3c1a0f84d15c698627acaba710292eb7c574bae66d99a0cb12f236e4bdf3b8ff998c119d9d2e24a821729a8f074e8d26f73
users_permission:
mailinglists_permission:
fname: Baran
last_login_ip:
site_permission:
last_login_at:
login:
sname: Olofsson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_002:
city: "Br\xC3\xA5landa"
- single_access_token:
+ single_access_token: 1Is4aPKS401krBlSDD7Z
last_request_at:
personal_number: 19810203-9909
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:26:52
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: r-Wjwf1Dbtqe5oSEQKt-
+ updated_at: 2010-01-26 18:21:35
zipcode: "46065"
main_interest_id: "3"
groups_permission:
club_id: "2"
board_position_id: "1"
id: "25"
current_login_ip:
street: Valldammsgatan 42
home_phone: 0521-9520867
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: f464267a0b07fda46e6ebc1e42e5a7f4ddba7992c230a814ca2d3f5cae79541f0da9f61c21195a94c195e38f3eccf7bd056263999047e3a04566040308d259c3
users_permission:
mailinglists_permission:
fname: Amalia
last_login_ip:
site_permission:
last_login_at:
login:
sname: Gustavsson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_014:
city: Nybro
- single_access_token:
+ single_access_token: mFlg5QnvGvSij7hU7TpA
last_request_at:
personal_number: 19450326-9377
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:28:44
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: Bc-8EaOIqSYd1d4TJ1mH
+ updated_at: 2010-01-26 18:21:35
zipcode: "0"
main_interest_id: "1"
groups_permission:
club_id: "9"
board_position_id: "1"
id: "137"
current_login_ip:
street: Valldammsgatan 42
home_phone: 0481-5635981
gender: male
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: bd184489c816e9713f0e7a80b877e1566c2069b92ecce03cce7ca08c6418c80ee1921eb3bcec1e49da2440a55f9cd919d8d0f7b13482bb7e1aa734c7014b1f93
users_permission:
mailinglists_permission:
fname: Svante
last_login_ip:
site_permission:
last_login_at:
login:
sname: Jansson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
users_003:
city: "F\xC3\x96LLINGE"
- single_access_token:
+ single_access_token: wZH5gvpBWujlA_Vmvhka
last_request_at:
personal_number: 19620629-3349
created_at: 2009-12-09 09:09:19
comments: ""
- crypted_password:
- perishable_token:
- updated_at: 2009-12-15 10:27:02
+ crypted_password: ad4755017100f0bcc24f016d0ef7b57cf3a76453ab477dd82059810463bf0a59
+ perishable_token: rpa8hlTBpAhcuftX8lC6
+ updated_at: 2010-01-26 18:21:35
zipcode: "83066"
main_interest_id: "1"
groups_permission:
club_id: "2"
board_position_id: "1"
id: "26"
current_login_ip:
street: "Norrfj\xC3\xA4ll 44"
home_phone: 0645-7595472
gender: female
failed_login_count:
type: Student
title_id: "1"
current_login_at:
login_count:
- persistence_token:
+ persistence_token: 508d9227ac884460493a5a07a66af16dd5a363fa116bf421a824c1f9f911e92090bb212728fa05d5c26bf4fb6a207261ec11a86256093f2888ead23d78165f46
users_permission:
mailinglists_permission:
fname: Agaton
last_login_ip:
site_permission:
last_login_at:
login:
sname: Johnsson
clubs_permission:
email: [email protected]
club_position_id: "1"
mobile_phone: ""
|
calmh/Register
|
a851f8305f889ce07fb30d7c8b8c101ce67bdb51
|
Fix from address
|
diff --git a/app/models/notifier.rb b/app/models/notifier.rb
index 7784ede..dda2582 100644
--- a/app/models/notifier.rb
+++ b/app/models/notifier.rb
@@ -1,11 +1,11 @@
class Notifier < ActionMailer::Base
default_url_options[:host] = "www.fiveforms.org"
def password_reset_instructions(user)
subject "Password Reset Instructions"
- from "TIA Register <[email protected]>"
+ from "[email protected]"
recipients user.email
sent_on Time.now
body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
end
end
|
calmh/Register
|
60d537df5d442aa5e49bd56dd638a0477491deb0
|
Files for password reset
|
diff --git a/app/controllers/password_resets_controller.rb b/app/controllers/password_resets_controller.rb
new file mode 100644
index 0000000..b4275ab
--- /dev/null
+++ b/app/controllers/password_resets_controller.rb
@@ -0,0 +1,46 @@
+class PasswordResetsController < ApplicationController
+ before_filter :load_user_using_perishable_token, :only => [:edit, :update]
+ before_filter :require_no_user, :only => [ :new, :edit ]
+
+ def new
+ render
+ end
+
+ def create
+ @user = User.find_by_login_or_email(params[:password_reset][:login])
+ if @user
+ @user.deliver_password_reset_instructions!
+ flash[:notice] = t(:Mailed_reset_instruction)
+ redirect_to new_user_session_path
+ else
+ flash[:notice] = t(:No_user_found)
+ render :action => :new
+ end
+ end
+
+ def edit
+ render
+ end
+
+ def update
+ data = params[:student]
+ data = params[:administrator] if data.nil?
+ @user.password = data[:password]
+ @user.password_confirmation = data[:password_confirmation]
+ if @user.save
+ flash[:notice] = t(:Password_updated)
+ redirect_to root_url
+ else
+ render :action => :edit
+ end
+ end
+
+ private
+ def load_user_using_perishable_token
+ @user = User.find_using_perishable_token(params[:id])
+ unless @user
+ flash[:notice] = t(:Could_not_load_account)
+ redirect_to root_url
+ end
+ end
+end
diff --git a/app/helpers/password_resets_helper.rb b/app/helpers/password_resets_helper.rb
new file mode 100644
index 0000000..0c9d96e
--- /dev/null
+++ b/app/helpers/password_resets_helper.rb
@@ -0,0 +1,2 @@
+module PasswordResetsHelper
+end
diff --git a/app/models/notifier.rb b/app/models/notifier.rb
new file mode 100644
index 0000000..7784ede
--- /dev/null
+++ b/app/models/notifier.rb
@@ -0,0 +1,11 @@
+class Notifier < ActionMailer::Base
+ default_url_options[:host] = "www.fiveforms.org"
+
+ def password_reset_instructions(user)
+ subject "Password Reset Instructions"
+ from "TIA Register <[email protected]>"
+ recipients user.email
+ sent_on Time.now
+ body :edit_password_reset_url => edit_password_reset_url(user.perishable_token)
+ end
+end
diff --git a/app/views/notifier/password_reset_instructions.erb b/app/views/notifier/password_reset_instructions.erb
new file mode 100644
index 0000000..e890b32
--- /dev/null
+++ b/app/views/notifier/password_reset_instructions.erb
@@ -0,0 +1,9 @@
+A request to reset your password has been made.
+If you did not make this request, simply ignore this email.
+If you did make this request just click the link below:
+
+<%= @edit_password_reset_url %>
+
+If the above URL does not work try copying and pasting it into your browser.
+If you continue to have problem please feel free to contact us.
+
diff --git a/app/views/password_resets/edit.html.haml b/app/views/password_resets/edit.html.haml
new file mode 100644
index 0000000..9e459de
--- /dev/null
+++ b/app/views/password_resets/edit.html.haml
@@ -0,0 +1,15 @@
+.block
+ .content
+ %h2.title= t:Reset_password
+ .inner
+ - form_for @user, :url => { :controller => 'password_resets', :action => 'update' }, :html => {:class => 'form'} do |f|
+ = f.hidden_field :perishable_token
+ .group
+ = f.label :password, t(:Password), :class => :label
+ = f.password_field :password, :class => 'text_field'
+ .group
+ = f.label :password_confirmation, t(:Confirm_Password), :class => :label
+ = f.password_field :password_confirmation, :class => 'text_field'
+ .group
+ = f.submit t(:Request_password_reset)
+
diff --git a/app/views/password_resets/new.html.haml b/app/views/password_resets/new.html.haml
new file mode 100644
index 0000000..27595ec
--- /dev/null
+++ b/app/views/password_resets/new.html.haml
@@ -0,0 +1,12 @@
+.block
+ .content
+ %h2.title= t:Reset_password
+ .inner
+ - form_for :password_reset, :url => {:action => 'create'}, :html => {:class => 'form'} do |f|
+ .group
+ = f.label :login, t(:Login_or_email), :class => 'label'
+ = f.text_field :login, :class => 'text_field'
+ %span.description= t(:Password_reset_descr)
+ .group
+ = f.submit t(:Request_password_reset)
+
|
calmh/Register
|
ee86f3dc7eff4917e3974ea2846950776ab8a752
|
Add missing translation
|
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 7f36e77..bedcbe6 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,182 +1,183 @@
en:
Register: Register
Students: Students
ID: ID
Name: Name
Grade: Grade
Statistics: Statistics
Num_Students: Number of Students
Group: Group
Personal_Num: Personal Number
Latest_Payment: Latest Payment
Time_since_grade: Time since graduation
Club_List: Clubs
New_Club: New Club
Edit_Club: Edit Club
Edit_Student: Edit Student
Email: Email
Home_phone: Home Phone
Mobile_phone: Mobile Phone
Street: Street
Zipcode: Zip Code
City: City
Title: Title
Comments: Comments
Sname: Surname
Fname: Name
Save: Save
Cancel: Cancel
red: red
yellow: yellow
green: green
blue: blue
black: black
unknown: unknown
none: none
silver: silver
junior: junior
or: or
Profile: Profile
Settings: Settings
Logout: Logout
Graduations: Graduations
Instructor: Instructor
Examiner: Examiner
Graduated: Graduated
Edit: Edit
Payments: Payments
Description: Description
Received: Received
Amount: Amount
Must_log_in: You must log in to access this page.
Log_in: Log in
Login: Login
Login_or_email: Login or email address
Password: Password
Remember_me: Remember me
Login_successful: Login successful
Logout_successful: Logout successful
Logged_in_since: Logged in since
Logged_in_from: Logged in from
Previous_login: Previous login
Previous_login_from: Previous login from
Num_Loginss: Number of Logins
Login_descr: Three or more characters
Edit_User: Edit User
Current_Grade: Current Grade
Held_Since: Held Since
Personal_Num_descr: Personal number (19700101-1234) or birthdate (19700101).
Phone_number_descr: Phone number (046-123456) or international phone number (+46 46-123456).
New_Student: New Student
Register_Graduation: Register Graduation
ago: ago
Send_Message: Send Message
Register_Payment: Register Payment
Acts_on_selected: Select on or more students above to act on them.
Show: Show
Links: Links
for: for
Num_Clubs: Number of Clubs
Change_Password: Change Password
Confirm_Password: Confirm Password
Group_List: Groups
All_Groups: Groups
New_Group: New Group
Edit_Group: Edit Group
Merge: Merge
Merge_descr: Select a different group here to merge this group.
User_List: Users
All_Users: Users
New_User: New User
Edit_clubs: Edit Clubs
Edit_groups: Edit Groups
Edit_Users: Edit Users
Edit_Mailing_Lists: Edit Mailing Lists
Gender: Gender
male: male
female: female
Male: Male
Female: Female
Gender_descr: Select a gender. If a complete personal number is filled in above, that wull be used to determine gender.
Read: Read
Write: Write
Delete: Delete
Club: Club
Global_Permissions: Global Permissions
Club_Permissions: Club Permissions
Group_merged: Group was successfully merged.
Could_not_complete_validation_errors: Could not complete the operation due to validation errors.
Group_updated: Group was successfully updated.
Group_created: Group was successfully created
Club_updated: Club was successfully updated.
Club_created: Club was successfully created.
Student_updated: Student was successfully updated.
Student_created: Student was successfully created.
User_updated: User was successfully updated.
User_created: User was successfully created.
Search: Search
All: All
Search_Students: Search Students
Search_Parameters: Search Parameters
Search_descr: Use the fields below to filter which students to see.
New_Graduation: New Graduation
Destroy: Destroy
Are_you_sure_club: Are you sure? The will club be deleted.
Are_you_sure_student: Are you sure? The student will be deleted.
Are_you_sure_user: Are you sure? The user will be deleted.
+ Are_you_sure_mailing_list: Are you sure? The mailing list will be deleted.
Mailing_Lists: Mailing Lists
New_Mailing_List: New Mailing List
Email: Email
Security: Security
Edit_Mailing_List: Edit Mailing List
Groups: Groups
Matched_x_students: Matched {{count}} students
Per_group: Per group
Per_gender: Per gender
Per_age: Per age
years: years
Members: Members
Public: Public
Private: Private
Security_descr: A public list can be joined by any user, a provate list can only be edited by an administrator.
Edit_User: Edit User
Edit_Mailing_List: Edit Mailing List
Address: Address
read: read
edit: edit
delete: delete
graduations: graduations
payments: payments
P_yes: Yes
P_no: No
User_created: User successfully created
Age: Age
Grade_category: Grade Category
Main_Interest: Main Interest
Per_Main_Interest: Per Main Interest
Club_Position: Club Position
Board_Position: Board Position
Per_Club_Position: Per Club Position
Per_Board_Position: Per Board Position
Users: Users
Percentage: Percentage
Edit_Site: Edit Site Settings
Site_settings_updated: The site settings were updated.
Site_Name: Site Name
Edit_own_permissions_descr: N.B! If you remove a permission from yourself, you will not be able to add it back again.
Login_invalid: Username or password is invalid.
Self_updated: Your new information has been saved.
New_Password: New Password
New_Password_descr: Set a new password, or leave blank to leave the existing password unchanged.
Default: Default
Default_ML_descr: If the mailing list is a default, new students will become members when they register.
Default_group_descr: If the mailing group is a default, new students will become members when they register.
Only_Active: Only Active
Site_Theme: Site Theme
No_payment: No payment registered
Validations: Validate data
Belongs_to_club: Belongs to club
Mailing_list_updated: Mailing list updated.
None: None
Export: Export
Export_as_CSV: Export as CSV
diff --git a/config/locales/sv.yml b/config/locales/sv.yml
index 1a7a18a..3661e53 100644
--- a/config/locales/sv.yml
+++ b/config/locales/sv.yml
@@ -1,260 +1,261 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
sv:
Register: Register
Students: Tränande
ID: ID
Name: Namn
Grade: Grad
Statistics: Statistik
Num_Students: Antal tränande
Group: Grupp
Personal_Num: Personnummer
Latest_Payment: Senaste inbetalning
Time_since_grade: Sen gradering
Club_List: Klubbar
New_Club: Ny klubb
Edit_Club: Redigera klubb
Edit_Student: Redigera tränande
Email: Epost
Home_phone: Telefon hemma
Mobile_phone: Telefon mobil
Street: Gatuadress
Zipcode: Postnummer
City: Stad
Title: Titel
Comments: Kommentarer
Sname: Efternamn
Fname: Förnamn
Save: Spara
Cancel: Avbryt
red: röd
yellow: gul
green: grön
blue: blå
black: svart
unknown: okänd
none: ingen
silver: silver
junior: junior
or: eller
Profile: Användarprofil
Settings: Inställningar
Logout: Logga ut
Graduations: Graderingar
Instructor: Instruktör
Examiner: Examinator
Graduated: Graderade
Edit: Redigera
Payments: Inbetalningar
Description: Förklaring
Received: Mottaget
Amount: Belopp
Must_log_in: Du måste logga in för att komma åt den här sidan.
Log_in: Logga in
Login: Användarnamn
Login_or_email: Användarnamn eller epostadress
Password: Lösenord
Remember_me: Kom ihåg mig
Login_successful: Du är nu inloggad.
Logout_successful: Du är nu utloggad.
Logged_in_since: Inloggad sedan
Logged_in_from: Loggade senast in från
Previous_login: Förra inloggningen
Previous_login_from: Loggade förra gången in från
Num_Loginss: Antal lyckade inloggningar
Login_descr: Bokstäver och siffror, minst två tecken.
Edit_User: Redigera användare
Current_Grade: Nuvarande grad
Held_Since: Sedan
Personal_Num_descr: Ange personnumer (19700102-1234) eller födelsedatum (19700102).
Phone_number_descr: Ange telefonnummer på formen 0123-456789 eller +45 12345678 för internationella nummer.
New_Student: Ny tränande
Register_Graduation: Registrera gradering
ago: sedan
Send_Message: Skicka meddelande
Register_Payment: Registrera inbetalning
Acts_on_selected: Nedanstående funktioner använder sig av de ovan markerade tränande. Markera en eller flera tränande för att skicka meddelanden eller registrera graderingar eller inbetalningar på dem samtidigt.
Show: Visa
Links: Val
for: för
Num_Clubs: Antal klubbar
Change_Password: Byt lösenord
Confirm_Password: Upprepa lösenordet
Group_List: Grupper
New_Group: Ny grupp
Edit_Group: Redigera grupp
Merge: Slå ihop
Merge_descr: Om du väljer en annan grupp här, så kommer eleverna i den här gruppen att flyttas till den valda gruppen, och den här gruppen raderas.
User_List: Användare
New_User: Ny användare
Edit_clubs: Redigera klubbar
Edit_groups: Redigera grupper
Edit_Users: Redigera användare
Edit_Mailing_Lists: Redigera epost-listor
Gender: Kön
male: man
female: kvinna
Male: Man
Female: Kvinna
Gender_descr: Om ett komplett personnumer matats in ovan kommer informationen i det att användas för att bestämma könet.
Read: Läsa
Write: Skriva
Delete: Radera
Club: Klubb
Global_Permissions: Globala rättigheter
Club_Permissions: Rättigheter per klubb
Group_merged: Gruppen har slagits ihop och raderats.
Could_not_complete_validation_errors: Det gick inte att fullfölja operationen på grund av valideringsfel. Detta är ett tecken på att all information inte är som den ska i databasen. Kontakta administratatören.
Group_updated: Gruppen har uppdaterats.
Group_created: Gruppen har skapats.
Club_updated: Klubben har uppdaterats.
Club_created: Klubben har skapats.
Student_updated: Eleven har uppdaterats.
Student_created: Eleven har skapats.
User_updated: Användaren har uppdaterats.
User_created: Användaren har skapats.
Search: Sök
All: Alla
Search_Students: Sök tränande
Search_Parameters: Sökparametrar
Search_descr: Använd fälten nedan för att begränsa listan på tränande till vänster.
New_Graduation: Ny gradering
Destroy: Radera
Are_you_sure_club: Ãr du säker? Klubben kommer att raderas, tillsammans med alla elever i den.
Are_you_sure_student: Ãr du säker? Eleven kommer att raderas.
Are_you_sure_user: Ãr du säker? Användaren kommer att raderas.
+ Are_you_sure_mailing_list: Ãr du säker? Epostlistan kommer att raderas.
Mailing_Lists: Epostlistor
New_Mailing_List: Ny epostlista
Email: Epostadress
Security: Säkerhet
Edit_Mailing_List: Redigera epostlista
Groups: Grupper
Matched_x_students: Hittade {{count}} tränande
Per_group: Per grupp
Per_gender: Per kön
Per_age: Per åldersgrupp
years: år
Members: Medlemmar
Public: Publik
Private: Privat
Security_descr: En publik lista kan enskilda elever välja att gå med i, men en privat lista kan endast en CI administrera medlemskap för.
Edit_User: Redigera användare
Edit_Mailing_List: Redigera epostlista
Address: Adress
read: se
edit: redigera
delete: radera
graduations: graderingar
payments: inbetalningar
P_yes: Ja
P_no: Nej
User_created: Användaren har skapats.
Age: Ã
lder
Grade_category: System
Main_Interest: Huvudinriktning
Per_Main_Interest: Per huvudinriktning
Club_Position: Föreningsbefattning
Board_Position: Styrelsebefattning
Per_Club_Position: Per föreningsbefattning
Per_Board_Position: Per styrelsebefattning
Users: Användare
Percentage: Andel
Edit_Site: Webbplatsinställningar
Site_settings_updated: Webbplatsens inställningar uppdaterades.
Site_Name: Webbplatsens namn
Edit_own_permissions_descr: OBS! Om du tar bort en rättighet från dig själv kommer du inte att kunna lägga till den igen.
Login_invalid: Användarnamn eller lösenord är ogiltigt.
Self_updated: Dina nya uppgifter har sparats.
New_Password: Nytt lösenord
New_Password_descr: Ange ett nytt lösenord eller lämna blankt för att inte ändra det nuvarande.
Default: Standardval
Default_ML_descr: Om epostlistan är ett standardval kommer nya elever att bli medlemmar på den när de skapas.
Default_group_descr: Om gruppen är ett standardval kommer nya elever att bli medlemmar i den när de skapas.
Only_Active: Endast aktiva
Site_Theme: Webbplatsens tema
No_payment: Ingen inbetalning registrerad
Validations: Validera data
Belongs_to_club: Tillhör klubb
Mailing_list_updated: Epostlistan har uppdateras.
None: Ingen
Export: Exportera
Export_as_CSV: Exportera som CSV
authlogic:
error_messages:
login_blank: kan inte vara tomt
login_not_found: är ogiltigt
login_invalid: får bara innehålla bokstäver och siffror
consecutive_failed_logins_limit_exceeded: För många felaktiga inloggningar. Kontot är blockerat.
email_invalid: måste se ut som en epostadress.
password_blank: kan inte vara tomt
password_invalid: är ogiltigt
not_active: Ditt konto är inte aktivt
not_confirmed: Ditt konto är inte konfirmerat
not_approved: Ditt konto är inte accepterat
no_authentication_details: You did not provide any details for authentication.
models:
user_session: Användarsession
attributes:
user_session:
login: användarnamn
email: epostadress
password: lösenord
remember_me: kom ihåg mig
activerecord:
errors:
models:
mailing_list:
attributes:
email:
taken: Epostadress upptagen
messages:
too_short: för kort
taken: upptaget
missing: saknas
blank: tomt
invalid: ogiltigt
incorrect_check_digit: felaktig kontrollsiffra
datetime:
distance_in_words:
about_x_years: ungefär %d år
over_x_years: over %d år
about_x_hours:
one: ungefär %d timme
other: ungefär %d timmar
less_than_x_minutes:
one: mindre än %d minut
other: mindre än %d minuter
x_minutes:
one: %d minut
other: %d minuter
x_months:
one: %d månad
other: %d månader
x_days:
one: %d dag
other: %d dagar
date:
order: [ :year, :month, :day ]
month_names: [~, Januari, Februari, Mars, April, Maj, Juni, Juli, Augusti, September, Oktober, November, December]
abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
abbr_day_names: [Sön, Mon, Tis, Ons, Tor, Fre, Lör ]
day_names: [Söndag, Mondag, Tisdag, Onsdag, Torsdag, Fredag, Lördag ]
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
|
calmh/Register
|
ce97b9b6f1bec305478a564b2e7bd185f1c603fd
|
Hamlify main layout + links and change version format
|
diff --git a/app/controllers/user_sessions_controller.rb b/app/controllers/user_sessions_controller.rb
index fd2d6a0..f3352fb 100644
--- a/app/controllers/user_sessions_controller.rb
+++ b/app/controllers/user_sessions_controller.rb
@@ -1,33 +1,32 @@
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_administrator, :only => :destroy
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
- # flash[:notice] = t(:Login_successful)
@user = @user_session.user
if @user.type == 'Student'
default = edit_student_path(@user)
elsif @user.type == 'Administrator'
default = clubs_path
default = club_path(@user.clubs[0]) if [email protected]_permission? && @user.clubs.length == 1
end
redirect_to default
else
flash[:warning] = t(:Login_invalid)
redirect_to new_user_session_path
end
end
def destroy
current_user_session.destroy
flash[:notice] = t(:Logout_successful)
redirect_to new_user_session_path
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index b4012b7..21ec7d3 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,50 +1,55 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def get_config(setting)
SiteSettings.get_setting(setting)
end
def grades
Grade.find(:all, :order => :level)
end
def grade_categories
GradeCategory.find(:all, :order => :category)
end
def titles
Title.find(:all, :order => :level)
end
def board_positions
BoardPosition.find(:all, :order => :id)
end
def club_positions
ClubPosition.find(:all, :order => :id)
end
def grade_str(graduation)
if graduation == nil
return "-"
else
return graduation.grade.description + " (" + graduation.grade_category.category + ")"
end
end
def groups
Group.find(:all, :order => :identifier)
end
def clubs
Club.find(:all, :order => :name)
end
def mailing_lists
MailingList.find(:all, :order => :description)
end
def version
- `git describe`.strip.sub(/-(\d+)-g([0-9a-f]+)/, ' (+\1, \2)')
+ `git describe`.strip.sub(/-(\d+)-g[0-9a-f]+$/, '+\1')
+ end
+
+ def active_string(active)
+ return 'active' if active
+ ''
end
end
diff --git a/app/views/application/_links.html.erb b/app/views/application/_links.html.erb
deleted file mode 100644
index b4abe97..0000000
--- a/app/views/application/_links.html.erb
+++ /dev/null
@@ -1,27 +0,0 @@
-<% active = controller.controller_name == 'clubs' || (controller.controller_name == "students" && controller.action_name != "search") -%>
-<li class="first<%= active ? ' active' : ''%>"><%= link_to t(:Club_List), clubs_path %></li>
-
-<% if current_user.clubs_permission? -%>
-<% active = controller.controller_name == 'students' && controller.action_name == "search" -%>
-<li class="<%= active ? ' active' : ''%>"><%= link_to t(:Search_Students), search_path %></li>
-<% end -%>
-
-<% if current_user.groups_permission? -%>
-<% active = controller.controller_name == 'groups' -%>
-<li class="<%= active ? ' active' : ''%>"><%= link_to t(:Group_List), groups_path %></li>
-<% end -%>
-
-<% if current_user.mailinglists_permission? -%>
-<% active = controller.controller_name == 'mailing_lists' -%>
-<li class="<%= active ? ' active' : ''%>"><%= link_to t(:Mailing_Lists), mailing_lists_path %></li>
-<% end -%>
-
-<% if current_user.users_permission? -%>
-<% active = controller.controller_name == 'administrators' -%>
-<li class="<%= active ? ' active' : ''%>"><%= link_to t(:User_List), administrators_path %></li>
-<% end -%>
-
-<% if current_user.site_permission? -%>
-<% active = controller.controller_name == 'application' -%>
-<li class="<%= active ? ' active' : ''%>"><%= link_to t(:Edit_Site), edit_site_path %></li>
-<% end -%>
diff --git a/app/views/application/_links.html.haml b/app/views/application/_links.html.haml
new file mode 100644
index 0000000..8a96f08
--- /dev/null
+++ b/app/views/application/_links.html.haml
@@ -0,0 +1,22 @@
+- active = active_string(controller.controller_name == 'clubs' || (controller.controller_name == "students" && controller.action_name != "search"))
+%li.first{:class => active}= link_to t(:Club_List), clubs_path
+
+- if current_user.clubs_permission?
+ - active = active_string(controller.controller_name == 'students' && controller.action_name == "search")
+ %li{:class => active}= link_to t(:Search_Students), search_path
+
+- if current_user.groups_permission?
+ - active = active_string(controller.controller_name == 'groups')
+ %li{:class => active}= link_to t(:Group_List), groups_path
+
+- if current_user.mailinglists_permission?
+ - active = active_string(controller.controller_name == 'mailing_lists')
+ %li{:class => active}= link_to t(:Mailing_Lists), mailing_lists_path
+
+- if current_user.users_permission?
+ - active = active_string(controller.controller_name == 'administrators')
+ %li{:class => active}= link_to t(:User_List), administrators_path
+
+- if current_user.site_permission?
+ - active = active_string(controller.controller_name == 'application')
+ %li{:class => active}= link_to t(:Edit_Site), edit_site_path
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
deleted file mode 100644
index 318acbc..0000000
--- a/app/views/layouts/application.html.erb
+++ /dev/null
@@ -1,63 +0,0 @@
-<!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" lang="en">
-<% cache('layout_header') do -%>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title><%=get_config(:site_name)%></title>
- <%= stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style" %>
- <%= stylesheet_link_tag 'web_app_theme_override' %>
-</head>
-<body>
- <div id="container">
- <div id="header">
- <h1><a href="/"><%=get_config(:site_name)%></a></h1>
- <% end -%>
- <div id="user-navigation">
- <ul>
- <% if current_user -%>
- <% if current_user.type == 'Administrator' -%>
- <li><%=link_to t(:Profile), administrator_path(current_user)%></a></li>
- <% end -%>
- <li><%=link_to t(:Logout), user_session_path, :method => :delete, :class => "logout"%></a></li>
- <% end -%>
- <% for locale in I18n.available_locales do -%>
- <% if locale.to_s != I18n.locale.to_s -%>
- <li><%=link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s %></li>
- <% end -%>
- <% end -%>
- </ul>
- <div class="clear"></div>
- </div>
- <div id="main-navigation">
- <ul>
- <%= render :partial => 'application/links' %>
- </ul>
- <div class="clear"></div>
- </div>
- </div>
- <div id="wrapper">
- <div class="flash">
- <% flash.each do |type, message| -%>
- <div class="message <%= type %>">
- <p><%= message %></p>
- </div>
- <% end -%>
- </div>
- <div id="main">
- <%= yield %>
- <div id="footer">
- <div class="block">
- <% cache('layout_footer') do %>
- <p><%=t:Register%> <%=version%>  |  <%=COPYRIGHT%></p>
- <% end %>
- </div>
- </div>
- </div>
- <div id="sidebar">
- <%= yield :sidebar %>
- </div>
- <div class="clear"></div>
- </div>
-</div>
-</body>
-</html>
diff --git a/app/views/layouts/application.html.haml b/app/views/layouts/application.html.haml
new file mode 100644
index 0000000..5b39c77
--- /dev/null
+++ b/app/views/layouts/application.html.haml
@@ -0,0 +1,44 @@
+!!!
+%html
+ - cache('layout_header') do
+ %head
+ %title= get_config(:site_name)
+ = stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style"
+ = stylesheet_link_tag 'web_app_theme_override'
+
+ %body
+ #container
+ #header
+ %h1
+ %a{ :href => root_path }= get_config(:site_name)
+ #user-navigation
+ %ul
+ - if current_user
+ - if current_user.type == 'Administrator'
+ %li= link_to t(:Profile), administrator_path(current_user)
+ %li=link_to t(:Logout), user_session_path, :method => :delete, :class => "logout"
+ - for locale in I18n.available_locales do
+ - if locale.to_s != I18n.locale.to_s
+ %li= link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s
+ .clear
+
+ - if controller.controller_name != 'user_sessions'
+ #main-navigation
+ %ul
+ = render :partial => 'application/links'
+ .clear
+
+ #wrapper
+ .flash
+ - flash.each do |type, message|
+ %div{ :class => "message " + type.to_s }
+ %p= message
+ #main
+ = yield
+ - cache('layout_footer') do
+ #footer
+ .block
+ %p #{t(:Register)} v#{version}  |  #{COPYRIGHT}
+
+ #sidebar= yield :sidebar
+ .clear
diff --git a/app/views/layouts/user_sessions.html.erb b/app/views/layouts/user_sessions.html.erb
deleted file mode 100644
index 8050ddd..0000000
--- a/app/views/layouts/user_sessions.html.erb
+++ /dev/null
@@ -1,48 +0,0 @@
-<!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" lang="en">
-<% cache('layout_header') do -%>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title><%=get_config(:site_name)%></title>
- <%= stylesheet_link_tag 'web_app_theme', "themes/" + SiteSettings.site_theme + "/style" %>
- <%= stylesheet_link_tag 'web_app_theme_override' %>
-</head>
-<body>
- <div id="container">
- <div id="header">
- <h1><a href="/"><%=get_config(:site_name)%></a></h1>
- <% end -%>
- <div id="user-navigation">
- <ul>
- <% for locale in I18n.available_locales do -%>
- <% if locale.to_s != I18n.locale.to_s -%>
- <li><%=link_to image_tag(locale.to_s + '.png'), '?locale=' + locale.to_s %></li>
- <% end -%>
- <% end -%>
- </ul>
- <div class="clear"></div>
- </div>
- </div>
- <div id="wrapper">
- <div class="flash">
- <% flash.each do |type, message| -%>
- <div class="message <%= type %>">
- <p><%= message %></p>
- </div>
- <% end -%>
- </div>
- <div id="main">
- <%= yield %>
- <div id="footer">
- <div class="block">
- <% cache('layout_footer') do %>
- <p><%=t:Register%> <%=version%>  |  <%=COPYRIGHT%></p>
- <% end %>
- </div>
- </div>
- </div>
- <div class="clear"></div>
- </div>
-</div>
-</body>
-</html>
diff --git a/test/fixtures/default_values.yml b/test/fixtures/default_values.yml
deleted file mode 100644
index dde78a5..0000000
--- a/test/fixtures/default_values.yml
+++ /dev/null
@@ -1,37 +0,0 @@
----
-default_values_001:
- created_at: 2009-12-21 14:42:36
- updated_at: 2009-12-22 22:19:00
- id: "1"
- value: "0"
- user_id: "164"
- key: |
- --- :only_active
-
-default_values_002:
- created_at: 2009-12-23 08:17:08
- updated_at: 2009-12-23 08:28:20
- id: "2"
- value: "300.0"
- user_id: "164"
- key: |
- --- :payment_amount
-
-default_values_003:
- created_at: 2009-12-23 08:17:08
- updated_at: 2009-12-23 08:17:08
- id: "3"
- value: HT 2009
- user_id: "164"
- key: |
- --- :payment_description
-
-default_values_004:
- created_at: 2009-12-23 08:17:08
- updated_at: 2009-12-23 08:28:20
- id: "4"
- value: 2009-09-28 00:00:00
- user_id: "164"
- key: |
- --- :payment_received
-
diff --git a/test/fixtures/schema_migrations.yml b/test/fixtures/schema_migrations.yml
deleted file mode 100644
index 49bc3a9..0000000
--- a/test/fixtures/schema_migrations.yml
+++ /dev/null
@@ -1,75 +0,0 @@
----
-schema_migrations_033:
- version: "20091221083610"
-schema_migrations_022:
- version: "20091215100823"
-schema_migrations_011:
- version: "20091122205907"
-schema_migrations_034:
- version: "20091221104820"
-schema_migrations_023:
- version: "20091215113914"
-schema_migrations_012:
- version: "20091206142332"
-schema_migrations_001:
- version: "20091114214935"
-schema_migrations_035:
- version: "20091221105424"
-schema_migrations_024:
- version: "20091215114003"
-schema_migrations_013:
- version: "20091206211602"
-schema_migrations_002:
- version: "20091114215240"
-schema_migrations_036:
- version: "20091221163400"
-schema_migrations_025:
- version: "20091215122735"
-schema_migrations_014:
- version: "20091209123034"
-schema_migrations_003:
- version: "20091114215344"
-schema_migrations_037:
- version: "20100112214206"
-schema_migrations_026:
- version: "20091215122750"
-schema_migrations_015:
- version: "20091211201003"
-schema_migrations_004:
- version: "20091114215418"
-schema_migrations_027:
- version: "20091215123131"
-schema_migrations_016:
- version: "20091212101045"
-schema_migrations_005:
- version: "20091122114459"
-schema_migrations_028:
- version: "20091215180402"
-schema_migrations_017:
- version: "20091213150952"
-schema_migrations_006:
- version: "20091122114634"
-schema_migrations_029:
- version: "20091216164227"
-schema_migrations_018:
- version: "20091214191011"
-schema_migrations_007:
- version: "20091122140935"
-schema_migrations_030:
- version: "20091216165147"
-schema_migrations_019:
- version: "20091214191214"
-schema_migrations_008:
- version: "20091122141155"
-schema_migrations_031:
- version: "20091216194600"
-schema_migrations_020:
- version: "20091214194233"
-schema_migrations_009:
- version: "20091122142532"
-schema_migrations_032:
- version: "20091221072544"
-schema_migrations_021:
- version: "20091214194404"
-schema_migrations_010:
- version: "20091122194115"
|
thijs/cl-sphinx-search
|
48eef193d8bc35208e648f518893f676feb86db5
|
Use version var
|
diff --git a/cl-sphinx-search.asd b/cl-sphinx-search.asd
index 08f1386..4ad6ef8 100644
--- a/cl-sphinx-search.asd
+++ b/cl-sphinx-search.asd
@@ -1,29 +1,36 @@
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;;; See the LICENSE file for licensing information.
(in-package #:cl-user)
(defpackage #:cl-sphinx-search-asd
(:use :cl :asdf))
(asdf:operate 'asdf:load-op :ieee-floats)
(asdf:operate 'asdf:load-op :cl-pack)
(in-package #:cl-sphinx-search-asd)
+
+(defvar *cl-sphinx-search-version* "0.0.1"
+ "A string denoting the current version of cl-sphinx-search.")
+
+(export '*cl-sphinx-search-version*)
+
+
(defsystem #:cl-sphinx-search
:name "CL-SPHINX-SEARCH"
- :version "0.0.1"
+ :version #.*cl-sphinx-search-version*
:maintainer "M.L. Oppermann <[email protected]>"
:author "M.L. Oppermann <[email protected]>"
:licence "To be determined"
:description ""
:long-description "CL-SPHINX-SEARCH is the Common Lisp connection layer to Sphinx Search <http://sphinxsearch.com/>"
:serial t
:components ((:file "package")
(:file "constants")
(:file "cl-sphinx-search"))
:depends-on (:iolib.sockets
:cl-pack
:babel))
diff --git a/package.lisp b/package.lisp
index ddbbe2f..173e263 100644
--- a/package.lisp
+++ b/package.lisp
@@ -1,104 +1,105 @@
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
;;;; See the LICENSE file for licensing information.
(in-package #:cl-user)
(defpackage #:cl-sphinx-search
(:use :cl :iolib.sockets :babel :cl-pack)
+ (:import-from :cl-sphinx-search-asd :*cl-sphinx-search-version*)
(:export #:set-server
#:set-limits
#:run-query
#:add-query
#:run-queries
#:last-error
#:last-warning
#:set-id-range
#:set-filter
#:set-filter-range
#:set-filter-float-range
#:max-query-time
#:set-geo-anchor
#:set-group-by
#:set-group-distinct
#:set-select
#:reset-filters
#:reset-group-by
#:reset-overrides)
(:documentation
"This package provides an interface to the search daemon (@em{searchd})
for @a[http://www.sphinxsearch.com/]{Sphinx}.
@begin[About Sphinx]{section}
From the site:
@begin{pre}
Sphinx is a full-text search engine, distributed under GPL version 2.
Commercial license is also available for embedded use.
Generally, it's a standalone search engine, meant to provide fast,
size-efficient and relevant fulltext search functions to other applications.
Sphinx was specially designed to integrate well with SQL databases and
scripting languages. Currently built-in data sources support fetching data
either via direct connection to MySQL or PostgreSQL, or using XML pipe
mechanism (a pipe to indexer in special XML-based format which Sphinx
recognizes).
As for the name, Sphinx is an acronym which is officially decoded as
SQL Phrase Index. Yes, I know about CMU's Sphinx project.
@end{pre}
@end{section}
@begin[Synopsis]{section}
@begin{pre}
(let ((sph (make-instance 'sphinx-client)))
(add-query sph \"test\")
(run-queries sph))
@end{pre}
@end{section}
@begin[One class]{section}
There is just one class:
@aboutclass{sphinx-client}
@end{section}
@begin[Methods]{section}
Setting options/parameters:
@aboutfun{set-server}
@aboutfun{set-limits}
Running queries:
@aboutfun{run-query}
@aboutfun{add-query}
@aboutfun{run-queries}
@end{section}
@begin[Acknowledgements]{section}
This port is based on Sphinx.pm version 0.22 (deployed to CPAN
@a[http://search.cpan.org/~jjschutz/Sphinx-Search-0.22/]{here}), which
itself says:
@begin{pre}
This module is based on Sphinx.pm (not deployed to CPAN) for
Sphinx version 0.9.7-rc1, by Len Kranendonk, which was in turn
based on the Sphinx PHP API.
@end{pre}
Also used was the api for python which was supplied with the source code
download for Sphinx Search v0.9.9-rc2, in the @code{api/} directory.
@b{Documentation}
This documentation was generated by @a[http://www.lichteblau.com/atdoc/doc/]{atdoc},
the documentation generation system written by David Lichteblau.
@end{section}
"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.