Handle money in databaes and javascript

This commit is contained in:
Tyler Renelle 2012-02-04 14:40:45 -05:00
parent 46e6a6f2ac
commit b4408f8cb7
8 changed files with 39 additions and 7 deletions

View file

@ -80,6 +80,11 @@ class HabitsController < ApplicationController
def vote
@habit = current_user.habits.find(params[:id])
# habit.vote() saves money to the user, this hack prevents having to
# reload current_user to catch that change
@habit.user=current_user
@habit.vote(params[:vote])
@score = current_user.habits.sum('score').to_i

View file

@ -26,4 +26,12 @@ module HabitsHelper
return link_to(text, { :action => "vote", :id => habit.id, :vote => dir }, :class=>style, :remote=>true)
end
def user_gold
current_user.money.to_i
end
def user_silver
number_with_precision(current_user.money, :precision=>1).split('.')[1]
end
end

View file

@ -21,15 +21,27 @@ class Habit < ActiveRecord::Base
# For positibe values, taper off with inverse log: y=.9^x
# Would love to use inverse log for the whole thing, but after 13 fails it hits infinity
sign = ( direction=='up' ? 1 : -1 )
value = 0
if self.score < 0
self.score += ( ( -0.1 * self.score + 1 ) * sign )
value = ( ( -0.1 * self.score + 1 ) * sign )
else
self.score += ( ( 0.9 ** self.score ) * sign )
value = ( ( 0.9 ** self.score ) * sign )
end
self.score += value
# also add money (we never take away money)
if direction=='up'
self.user.money += value
self.user.save
end
# up/down -voting as checkbox & assigning as done, 2 birds one stone
if(self.habit_type==Habit::DAILY)
self.done = true if direction=='up'
self.done = false if direction=='down'
end
save
end
end

View file

@ -0,0 +1,4 @@
<div id="money">
<%= user_gold %><%= image_tag('coin_single_gold.png') %>
<%= user_silver %><%= image_tag('coin_single_silver.png') %>
</div>

View file

@ -1,4 +1,4 @@
<div id="progressbar" style="width:30%;"><span id="tnl"><%= score %>/100</span></div>
<div id="progressbar" style="width:30%;"><span id="tnl">(Level 1)&nbsp;&nbsp;&nbsp;<%= score %>/100</span></div>
<script>
$(function() {
$( "#progressbar" ).progressbar({

View file

@ -41,10 +41,7 @@
<div class="block">
<div class='content'>
<h2 class='title'>Store
<div id="money">
<%= @score %><%= image_tag('coin_single_gold.png') %>
<%= @score %><%= image_tag('coin_single_silver.png') %>
</div>
<%= render 'money'%>
</h2>
<div class='inner'>
</div>

View file

@ -1,2 +1,3 @@
$('#habit_<%= @habit.id %>').replaceWith("<%= escape_javascript(render :partial => "habit", :locals => { :habit => @habit }) %>");
$('#progressbar').replaceWith("<%= escape_javascript(render :partial => "progressbar", :locals => { :score => @score }) %>");
$('#money').replaceWith("<%= escape_javascript(render 'money') %>");

View file

@ -0,0 +1,5 @@
class AddMoneyToUser < ActiveRecord::Migration
def change
add_column :users, :money, :float, :default=>0.0
end
end