This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(document).ready(function () { | |
$("form").on('submit', function(e){ | |
e.preventDefault(); | |
$.ajax({ | |
url: $(this).attr('action'), | |
method: $(this).attr('method'), | |
}).done(function(response) { | |
$("#die").html(response); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<img src="/<%= @roll.value %>.png" title="<%= @roll.value %>" alt="the roll"> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="container"> | |
<h1>Simplest Possible AJAX</h1> | |
<p>This contrived app will simulate a roll of a 6-sided die.</p> | |
<form method="post" action="/rolls"> | |
<input type="submit" value="Roll the Die"> | |
</form> | |
<div id="die"> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
get '/' do | |
erb :index | |
end | |
post '/rolls' do | |
value = params[:value] ? params[:value].to_i : nil | |
@roll = value ? Roll.create({ value: value }) : Roll.create | |
erb :die, layout: false #response is what's rendered? | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simple table that represents the roll of a 6-sided die | |
class Roll < ActiveRecord::Base | |
attr_accessible :value | |
validates :value, :inclusion => { :in => (1..6), :message => "must be between 1 and 6" } | |
after_initialize :roll_if_value_is_nil | |
private | |
# If the user passes-in a "value", let's use it. Otherwise, we'll generate a random one. | |
def roll_if_value_is_nil | |
self.value = (rand(6) + 1) if not self.value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment