Last active
August 29, 2015 14:00
-
-
Save catm705/11047278 to your computer and use it in GitHub Desktop.
Palindrome Rails App
This file contains hidden or 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
---------------------------------------------------------- | |
Palindrome.rb | |
---------------------------------------------------------- | |
# In ActiveRecord docs as 'validates_with' | |
class ValidPalindrome < ActiveModel::Validator | |
def validate(record) | |
test_string = record.text | |
unless test_string == test_string.reverse | |
record.errors[:text] << 'This is not a Palindrome.' | |
end | |
end | |
end | |
class Palindrome < ActiveRecord::Base | |
before_save :isPalindrome? | |
validates :text, presence: true, uniqueness: true | |
validates_length_of :text, minimum: 2 | |
# include ActiveModel::Validations | |
validates_with ValidPalindrome | |
def isPalindrome? | |
test_string = self.text | |
test_string = test_string.gsub(" ", "").downcase | |
return test_string == test_string.reverse | |
end | |
end | |
---------------------------------------------------------- | |
routes.rb | |
---------------------------------------------------------- | |
root 'palindromes#index' | |
resources :palindromes | |
---------------------------------------------------------- | |
index.html.erb | |
---------------------------------------------------------- | |
<h1>Palindromes</h1> | |
<% if flash[:notice]%> | |
<div><%= flash[:notice] %> </div> | |
<% end %> | |
<%= form_for(@palindrome) do |f| %> | |
<%= f.label :text %> | |
<%= f.text_field :text %> | |
<%= f.label :letters %> | |
<%= f.text_field :letters %> | |
<%= f.submit %> | |
<% end %> | |
<table> | |
<tbody> | |
<% @palindromes.each do |p| %> | |
<tr> | |
<td><%= p.text %></td> | |
<td><%= p.letters %></td> | |
</tr> | |
<% end %> | |
</tbody> | |
</table> | |
---------------------------------------------------------- | |
palindrome_controller.rb | |
---------------------------------------------------------- | |
class PalindromesController < ApplicationController | |
def index | |
@palindromes = Palindrome.all | |
@palindrome = Palindrome.new | |
end | |
# def new | |
# end | |
def create | |
@palindrome = Palindrome.new(palindrome_params) | |
if @palindrome.save | |
redirect_to root_path | |
else | |
# flash[:notice] ="Your Palindrome didn't save." | |
redirect_to root_path, notice: @palindrome.errors.messages[:text].first | |
end | |
end | |
private | |
def palindrome_params | |
params.require(:palindrome).permit( | |
:text, | |
:letters | |
) | |
end | |
end | |
---------------------------------------------------------- | |
---------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment