Feeds:
Posts
Comments

Archive for the ‘Days @ Slashprog’ Category

Greetings!

Today i learnt a bit on HTML, CSS and then proceeded with Chapter 10 of Learn Rails by Example

In HTML i worked with image tag <img> from  w3schools

I learnt the following things in <img> tag

  • <img> tag is used to insert an image into an HTML document
  • There is no closing tag for it.
  • Contains common attributes such as src, alt, width, height, border
  • src – specifies the path of the image
  • alt – specifies the alternate text for the image
  • width, height – specifies the dimension for the image
  • border – sets the border for an image

To insert an image into an HTML document, i just followed the code to display the image in browser

<html>
<body>

<img border="0" src="/home/rajee/animal.jpg" alt="Deer" width="100" height="100" />

</body>
</html>

Then i switched to learn CSS from CSS CookBook by Christopher Schmitt available in our library

The book covers nearly 500 pages

I set a goal to complete 5 pages per day.

Though its a too too small small goal, i want to follow it everday with good understanding of my workarounds. And this is my real goal 🙂 🙂

From yesterday i started to learn CSS

So, today i completed 10 pages from the book.

I came across the following two selectors in CSS cookbook

  • Type Selectors
  • Class Selectors

Type Selectors

It represents the HTML tags or the elements

Example

h1 { font-size:100%; }

body { background-color : red; }

Class Selectors:

It is used to apply the same CSS rule many times to different elements.

Example

<html>
 <head>
 <title>CSS Cookbook</title>
 <style type="text/css">
 .warning
 {
 font-weight:bold;
 }
 </style>
 </head>
 <body>
 <p>A para <a href="http://csscookbook.com">link</a>.
 <p>Second para illustrating the <em>class selector</em> example</p>
 </body>
</html>

Then i started to watch and work with the rails screencast

Previously, i stopped in quarter portion of Chapter 10 ( i.e., i just worked with first half an hour of the tutorial )

I resumed from where i left and watched next one hour lesson

In my workaround i learnt how to implement a bit of security model while updating users

The first step is to protect pages from unauthorised access by requiring signing in ( ie., if someone wants to access edit page, he/she should be redirected to sign-in page )

It is done using before_filter

Writing test cases in users_controller_spec.rb


describe "authentication of edit/update actions" do

 before(:each) do
 @user = Factory(:user)
 end

 it "should deny access to 'edit'" do
 get :edit, :id => @user
 response.should redirect_to(signin_path)
 end

 it "should deny access to 'update'" do
 put :update, :id => @user, :user => { }
 response.should redirect_to(signin_path)
 end
 end

Adding before_filter in users_controller.rb


before_filter :authenticate, :only => [:edit, :update]

def authenticate
 redirect_to signin_path unless signed_in?
 end

By 3.45p.m., we gathered for a SCRUM Meet and i told like as i exlpored on HTML,CSS,Chapter 10 of Learn Rails by Example

Will be continue to work with these technologies tomorrow 🙂

Read Full Post »

Greetings!

Today i started to watch Chapter 10 of Learn Rails by Example

Its a very long screencast approximately about 2 and half hours

I just watched and practised the first half an hour of the screencast

This lesson completes updating, deleting and showing users

The first step is to write test case for the presence of Edit page

Edit spec/controllers/users_controller_spec.rb


describe "GET 'edit'"do

 before(:each) do
 @user = Factory(:user)
 test_sign_in(@user)
 end

 it "should be successful" do
 get :edit, :id => @user
 response.should be_success
 end

 it "should have the right title" do
 get :edit, :id => @user
 response.should have_selector('title', :content => "Edit user")
 end

it "should have a link to change the Gravatar" do
 get :edit, :id => @user
 response.should have_selector('a', :href => 'http://gravatar.com/emails',
 :content => "change")
 end

 end

Add a edit action in app/controllers/users_controller.rb


def edit
 @user = User.find(params[:id])
 @title = "Edit user"
 end

Create a template to describe the edit form

The edit form is similar to new.html.erb.

It also contains a gravatar image link to change the image

edit.html.erb files looks like as follows


<h1>Edit User</h1>

<%= form_for(@user) do |f| %>
 <%= render 'shared/error_messages' %>
 <div>
 <%= f.label :name %><br />
 <%= f.text_field :name %>
 </div>


 <div>
 <%= f.label :email %><br />
 <%= f.text_field :email %>
 </div>

 <div>
 <%= f.label :password %><br />
 <%= f.password_field :password %>
 </div>

 <div>
 <%= f.label :password_confirmation, "Confirmation" %><br />
 <%= f.password_field :password_confirmation %>
 </div>

 <div>
 <%= f.submit "Update" %>
 </div>

<% end %>

<div>
 <%= gravatar_for @user %>
 <a href="http://gravatar.com/emails" target=_blank>change</a>
</div>

Will be continued working with Chapter 10

Read Full Post »

Hai,

Today we ( teammates ) spent time with our mentor Chandrashekar sir 🙂

We discussed with the user stories for our next project

While talking about it, our sir mentored us in a topic, “Time Management

He told about how to manage the time to make us productive on every day.

I recollected my friend, Shrini’s words, who use to mentor me then for a good career

Iam impressed by the following lines from our sir’s talk

If there is no one to assign a work for you, do self-plan and assign work for ourselves, so that you will get more interested to do it, rather than for others

Thanks for a wonderful talk sir

After the  class gets over, i started to watch Chapter 10 of Learn Rails by Example

This lesson is nearly 2 and 1/2 hour video

I have watched only one hour video but didnt work on it.

Hope to watch and work it out on the next working day

Read Full Post »

Hai,

Today i completed watching and working with Chapter 9 of Learn Rails by Example

I learnt on how to generate a successful Sign up, Sign in and Sign out methodologies

But i faced show stoppers in this lesson.

Hope, it will get solved working with it one more time and reading the book

The first step in  the development of Sign in and Sign out is to generate a session controller

Generate session controller


rails generate controller Sessions new

Modify the routes.rb The next step is to modify the routes.rb file to include the resource, sessions

resources :sessions
match '/signin', :to => 'sessions#new'
match '/signout' :to => 'sessions#destroy'

Creating Sign-in form


<h1>Sign in</h1>

<%= form_for(:session, :url => sessions_path) do |f| %>

<div>
 <%= f.label :email %><br />
 <%= f.text_field :email %>
 </div>
 <div>
 <%= f.label :password %><br />
 <%= f.password_field :password %>
 </div>
 <div>
 <%= f.submit "Sign in" %>
 </div>
 <% end %>

<p>New user? <%= link_to "Sign up now!", signup_path %></p>


This tutorial introduced me to important concepts such as cookies, authentication

I thought of updating the code of what i practised today, but i faced a problem in updating my git repository

When i gave the git merge sign-in-out command, received the following error

Error

Updating 77e2668..3db6c58
error: Your local changes to the following files would be overwritten by merge:
webrat.log
Please, commit your changes or stash them before you can merge.
Aborting

I searched to solve it but couldn’t end up

Hope to solve it soon and will share my learning experience with Chapter 9.

By 3:45 p.m., we gathered for a SCRUM meet, and i told as i worked with Chapter 9.

So far, i have completed learning nine lessons, and will be continuing with Chapter 10 :)


Read Full Post »

Hai

Today i worked the exercises at the end of Chapter 8 of Learn Rails by Example and watched the Chapter 9 screencast

Working with Chapter 8 Exercises

Question 1:

Write tests to check for the presence of each field (name, email, password, password_confirmation) on the signup form.

Solution


require 'spec_helper'
describe UsersController do
render_views
describe "GET 'new'" do

it "should have a name field" do
 get :new
 response.should have_selector("input[name='user[name]'][type='text']")
 end

 it "should have an email field" do
 get :new
 response.should have_selector("input[name='user[email]'][type='text']")
 end

 it "should have a password field" do
 get :new
 response.should have_selector("input[name='user[password]'][type='password']")
 end

 it "should have a password confirmation field" do
 get :new
 response.should have_selector("input[name='user[password_confirmation]'][type='password']")
 end

 end

Since i dont know to give a solution for Question 2, i skipped it and moved to Question 3

Question 3

Refine the code of ‘flash HTML’ in application.html.erb using content_tag helper

Solution

<% flash.each do |key, value| %>
<%= content_tag(:div, value, :class => "flash #{key}") %>
<% end %>

Then i started to watch Chapter 9 screencast.

It completes the sign in and sign out mechanism for the application

I didnt start to work on it.

By 4:00 p.m. we had a SCRUM meet and i told as i worked with Chapter 8 exercises and watched Chapter 9 tutorial

Will be start to work on Chapter 9 by tomorrow 🙂

Read Full Post »

Greetings!

Today i completed working with Chapter 8 of Learn Rails by Example

From this lesson, i learnt to create a functioning ‘Sign Up‘ form

The first step is to write test cases matching the valid information entered by the user

Writing success test case if the attributes are valid

spec/controllers/users_controller_spec.rb


describe "success" do

 before(:each) do
 @attr = { :name => "New User", :email => "user@example.com",
 :password => "foobar", :password_confirmation => "foobar" }
 end

 it "should create a user" do
 lambda do
 post :create, :user => @attr
 end.should change(User, :count).by(1)
 end

 it "should redirect to the user show page" do
 post :create, :user => @attr
 response.should redirect_to(user_path(assigns(:user)))
 end

 it "should have a welcome message" do
 post :create, :user => @attr
 flash[:success].should =~ /welcome to the sample app/i
 end

Add  code to save the user.

It is included inside create method in app/controllers/users_controller.rb


def create
 @user = User.new(params[:user])
 if @user.save
 redirect_to @user, :flash => { :success => "Welcome to the Sample App!"}
 else
 @title = "Sign up"
 render 'new'
 end

 end

Then wrote integration test for the Sign up form


rails generate integration_test users

Writing integration tests cases in spec/requests/users_spec.rb


require 'spec_helper'

describe "Users" do

 describe "signup" do

 describe "failure" do

 it "should not make a new user" do
 lambda do
 visit signup_path
 fill_in "Name",         :with => ""
 fill_in "Email",         :with => ""
 fill_in "Password",     :with => ""
 fill_in "Confirmation", :with => ""
 click_button
 response.should render_template('users/new')
 response.should have_selector('div#error_explanation')
 end.should_not change(User, :count)
 end

 end

 describe "success" do

 it "should make a new user" do
 lambda do
 visit signup_path
 fill_in "Name",         :with => "Example User"
 fill_in "Email",         :with => "user@example.com"
 fill_in "Password",     :with => "foobar"
 fill_in "Confirmation", :with => "foobar"
 click_button
 response.should have_selector('div.flash.success',
 :content => "Welcome")
 response.should render_template('users/show')
 end.should change(User, :count).by(1)
 end

 end

 end

end

Here’s my updated Git and Heroku URL’s

Git URL : https://github.com/rajee/sample_app

Heroku URL : http://floating-river-137.heroku.com/

By 3:45 p.m., we gathered for a SCRUM meet and i told as completed working with Chapter 8

Our mentor, Chandrashekar sir asked us to go through a ReadySet templates ( http://readyset.tigris.org/ )

After the meet, i explored a little bit on it.

ReadySet template is a open source project consists of project management templates helpful in documenting the project.

By tomorrow, i will continue my rails learning process from Chapter 9 🙂

Read Full Post »

Hai

Since we had a power cut in the morning for 3 hours i started to work from 1p.m.

Today i watched and worked with half of Chapter 8 – Learn Rails by Example

So far, this lesson taught me

  • How to create a Sign Up form ?
  • To write a failure test case if the atrributes are invalid
  • How to display the error messages in top of the form ?

Creating a Sign Up form

Edit app/views/users/new.html.erb

 


<h1>Sign up</h1>

<%= form_for(@user) do |f| %>
 <%= render 'shared/error_messages' %>    #render another form to show error messages
 <div>
 <%= f.label :name %><br />
 <%= f.text_field :name %>
 </div>

 <div>
 <%= f.label :email %><br />
 <%= f.text_field :email %>
 </div>

 <div>
 <%= f.label :password %><br />
 <%= f.password_field :password %>
 </div>

 <div>
 <%= f.label :password_confirmation, "Confirmation" %><br />
 <%= f.password_field :password_confirmation %>
 </div>

 <div>
 <%= f.submit "Sign up" %>
 </div>

<% end %>

Add a method create in app/controllers/users_controller.rb


def create
 @user = User.new(params[:user])
 if @user.save
 #Handle a successful save.
 else
 @title = "Sign up"
 render 'new'
 end
 end

Writing a failure test case for invalid data

Edit the file spec/controllers/users_controller_spec.rb


describe "POST 'create'" do

 describe "failure" do

 before(:each) do
 @attr = { :name => "", :email => "", :password => "",
 :password_confirmation => "" }
 end

 it "should have the right title" do
 post :create, :user => @attr
 response.should have_selector('title', :content => "Sign up")
 end

 it "should render the 'new' page" do
 post :create, :user => @attr
 response.should render_template('new')
 end

 it "should not create a user" do
 lambda do
 post :create, :user => @attr
 end.should_not change(User, :count)
 end

 end
 end

 

Displaying error information

Create a folder called shared in app/views.

Then create a partial _error_messages.html.erb in app/views/shared

This file is rendered in app/views/users/new.html.erb


<% if @user.errors.any? %>
<div id="error_explanation">
<h2>
<%= pluralize(@user.errors.count, "error") %>
prohibited this user from being saved:
</h2>
<p>There were problems with the following fields:</p>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>

</div>
<% end %>

 

By 4:40 p.m. we gathered for a SCRUM meet and i told as i was working with Chapter 8

Will try to complete the rest of this chapter by tomorrow


Read Full Post »

Greetings

Today i completed watching and working with Chapter 7 of Learn Rails by Example

This lesson introduced me to learn various concepts such as

  • How to authenticate users using password
  • Migrations, Validations
  • Virtual Attributes
  • Private Methods
  • Active Record Callback
  • Password encryption

The first step is to include the two attributes password, password_confirmation in the User model

These attributes are added using the concept of Virtual Attributes

Virtual attributes doesn’t exist in the database

It is available only in memory.

Virtual attribute is achieved using attr_accessor

Edit the user.rb to include ‘password’ ( virtual ) attribute


attr_accessor :password

password_conformation attribute is automatically added as a virtual attribute by using the following code in user.rb


validates :password, :conformation => true

Then i followed the screencast to write the test cases for the ‘password‘ attributes

All the test cases should be inside spec/models/user_spec.rb

Password Attributes Test Cases


describe "passwords" do

 before(:each) do
 @user = User.new(@attr)
 end

 it "should have a password attribute" do
 @user.should respond_to(:password)
 end

 it "should have a password confirmation attribute" do
 @user.should respond_to(:password_confirmation)
 end
 end

Password Validations Test Cases


describe "password validations" do

 it "should require a password" do
 User.new(@attr.merge(:password => "", :password_confirmation => "")).
 should_not be_valid
 end

 it "should require a matching password confirmation" do
 User.new(@attr.merge(:password_confirmation => "invalid")).
 should_not be_valid

 end

 it "should reject short passwords" do
 short = "a" * 5
 hash = @attr.merge(:password => short, :password_confirmation => short)
 User.new(hash).should_not be_valid
 end

 it "should reject long passwords" do
 long = "a" * 41
 hash = @attr.merge(:password => long, :password_confirmation => long)
 User.new(hash).should_not be_valid
 end
 end

To store a password which must be encrypted, we need to add a column( encrypted_password )  in the database

To implement it, we need to run the migration command


rails generate migration add_password_to_users encrypted_password:string

Before saving the password, the encrypted password in the database must be compared and equal to the encrypted version of submitted password.

To have a secure password, a hashing algorithm called SHA2 and salt is used

Salt is a combination of current time and user password

Salt is added by running a migration command


rails generate migration add_salt_to_users salt:string

Password Encryption Test Cases


describe "password encryption" do

 before(:each) do
 @user = User.create!(@attr)
 end

 it "should have an encrypted password attribute" do
 @user.should respond_to(:encrypted_password)
 end

 it "should set the encrypted password attribute" do
 @user.encrypted_password.should_not be_blank
 end

 it "should have a salt" do
 @user.should respond_to(:salt)
 end

 describe "has_password? method" do

 it "should exist" do
 @user.should respond_to(:has_password?)
 end

 it "should return true if the passwords match" do
 @user.has_password?(@attr[:password]).should be_true
 end

 it "should return false if the passwords don't match" do
 @user.has_password?("invalid").should be_false
 end
 end

 describe "authenticate method" do

 it "should exist" do
 User.should respond_to(:authenticate)
 end

 it "should return nil on email/password mismatch" do
 User.authenticate(@attr[:email], "wrongpass").should be_nil
 end

 it "should return nil for an email address with no user" do
 User.authenticate("bar@foo.com", @attr[:password]).should be_nil
 end

 it "should return the user on email/password match" do
 User.authenticate(@attr[:email], @attr[:password]).should == @user
 end

 end
 end

The user.rb file must be modified to looks as below


# == Schema Information
# Schema version: 20110216065316
#
# Table name: users
#
#  id                 :integer         not null, primary key
#  name               :string(255)
#  email              :string(255)
#  created_at         :datetime
#  updated_at         :datetime
#  encrypted_password :string(255)
#

class User < ActiveRecord::Base
 attr_accessor :password
 attr_accessible :name, :email, :password, :password_confirmation

 email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

 validates :name,  :presence => true,
 :length => { :maximum => 50 }
 validates :email, :presence => true,
 :format => { :with => email_regex },
 :uniqueness => { :case_sensitive => false }

 validates :password, :presence => true,
 :confirmation => true,
 :length => { :within => 6..40 }

 before_save :encrypt_password

 def has_password?(submitted_password)
 encrypted_password == encrypt(submitted_password)
 end

 class << self
 def authenticate(email, submitted_password)
 user =  find_by_email(email)
 return nil if user.nil?
 return user if user.has_password?(submitted_password)
 end
 end

 private

 def encrypt_password
 self.salt = make_salt if new_record?
 self.encrypted_password = encrypt(password)
 end

 def encrypt(string)
 secure_hash("#{salt}--#{string}")
 end

 def make_salt
 secure_hash("#{Time.now.utc}--#{password}")
 end

 def secure_hash(string)
 Digest::SHA2.hexdigest(string)
 end

end

To add an image to our application we need to include a gravatar gem in Gemfile

Edit the Gemfile

gem ‘gravatar_image_tag’, ‘0.1.0’

and run bundle install

Git URL : https://github.com/rajee/sample_app

Heroku URL : http://floating-river-137.heroku.com/users/1

By 3:45 p.m. we had a SCRUM meet and i told as i completed working with Chapter 7

Have to continue my learning with a new lesson ( Chapter 8 ) by tomorrow 🙂 🙂

Read Full Post »

Hai

Today i completed working with Chapter 6 Learn Rails by example

In the second half of Chapter 6, i learnt how to validate the name and email by writing the test code

The ‘name’ attribute is tested for its presence and length

The ’email’ attribute is tested for its presence, format and uniqueness ( ignoring the case sensitive )

The email format is validated using Rubular

At the end of this lesson, the file app/models/user.rb, looks as below


# == Schema Information
# Schema version: 20110210093610
#
# Table name: users
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  email      :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class User < ActiveRecord::Base
 attr_accessible :name, :email

 email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

 validates :name,  :presence => true,
 :length => { :maximum => 50 }
 validates :email, :presence => true,
 :format => { :with => email_regex },
 :uniqueness => { :case_sensitive => false }
end

The file spec/models/user_spec.rb looks as follows


require 'spec_helper'

describe User do

 before(:each) do
 @attr = { :name => "Example User", :email => "user@example.com" }
 end

 it "should create a new instance given a valid attribute" do
 User.create!(@attr)
 end

 it "should require a name" do
 no_name_user = User.new(@attr.merge(:name => ""))
 no_name_user.should_not be_valid
 end

 it "should require an email address" do
 no_email_user = User.new(@attr.merge(:email => ""))
 no_email_user.should_not be_valid
 end

 it "should reject names that are too long" do
 long_name = "a" * 51
 long_name_user = User.new(@attr.merge(:name => long_name))
 long_name_user.should_not be_valid
 end

 it "should accept valid email addresses" do
 addresses = %w[user@foo.com THE_USER@foo.bar.org first.last@foo.jp]
 addresses.each do |address|
 valid_email_user = User.new(@attr.merge(:email => address))
 valid_email_user.should be_valid
 end
 end

 it "should reject invalid email addresses" do
 addresses = %w[user@foo,com user_at_foo.org example.user@foo.]
 addresses.each do |address|
 invalid_email_user = User.new(@attr.merge(:email => address))
 invalid_email_user.should_not be_valid
 end
 end

 it "should reject duplicate email addresses" do
 User.create!(@attr)
 user_with_duplicate_email = User.new(@attr)
 user_with_duplicate_email.should_not be_valid
 end

 it "should reject email addresses identical up to case" do
 upcased_email = @attr[:email].upcase
 User.create!(@attr.merge(:email => upcased_email))
 user_with_duplicate_email = User.new(@attr)
 user_with_duplicate_email.should_not be_valid
 end
end

Then i learnt how to display the debug information on the web page

This information is only visible in development environment, not in production

To do it, add the code in app/views/layouts/application.html.erb


<%= debug(params) if Rails.env.development? %>

By 3:45 p.m we had a SCRUM Meet and i told as i done with Chapter 6 🙂

After the meet i started to watch Chapter 7 which will be continued tomorrow too.

Read Full Post »

Greetings!

Today i completed watching Chapter 6 of Learn Rails by Example

It lasted for 1 hour and 30 minutes

This chapter is dedicated to modeling ( in database level ) and viewing users for the application

I worked on the first 30 minutes of the video tutorial

I learnt to do database operations ( Create, Retrieve, Update and Delete ( CRUD ) ) from the rails console

CRUD is carried out by Active Record which is  a default library in rails for database purposes

Here’s a summary of my learnings today

Generating a user model


rails generate model User name:string email:string

rake db:migrate

This will create a users table in database with the two attributes – name, email

To view the database attributes generated by the above command we need to include a gem called annotate-model in Gemfile

Edit the Gemfile


gem annotate-models

and then run bundle install

Now open the terminal and run the command as below

[rajee@localhost sample_app]$ annotate

Annonated User

The results are viewed in app/models/user.rb


# == Schema Information
# Schema version: 20110210093610
#
# Table name: users
#
#  id         :integer         not null, primary key
#  name       :string(255)
#  email      :string(255)
#  created_at :datetime
#  updated_at :datetime
#

class User < ActiveRecord::Base
end

Inside the User class we need to define what attributes are visible/accessed to the outside world

This is done using attr_accessible

Here name and email are accessed


class User < ActiveRecord::Base
 attr_accessible :name, :email
end

I opened a new terminal and typed the command within the project directory tail -f log/development.log to  view log files

I played with database from the console rails  console


#Creating a new user

user = User.new( :name=> "San Jose", :email => "jose@example.com" )

#Storing in database
user.save
=> true
#Creating and storing the user in database using 'create' method

user = User.create ( :name=> "San Jose", :email => "jose@example.com" )

#Retrieving the first user

User.find(1)

#Retrieving all users

User.all

#deleting the user

user.destroy

#updating the user

user.update_attributes(:name => 'The Dude', :email => 'dude@abides.org')

By 3:50 p.m. we had a SCRUM Meet and i told as i watched the whole Chapter 6 and worked a half in it

Since i didnt complete working with this chapter i will be continuing with it tomorrow

Read Full Post »

Older Posts »