Wednesday, 29 August 2012

Validations,and certain others!!

Validations:
    Validations can be either done in the front end using javascript or at the back end before putting the data in the server.Which is better??
If all validations are done in the javascript "Disable javascript option can remove the vaildations.But if all the validations are done by the server there will be overhead in the server.So a balance between the 2 should be accomplished.
      Various options that are available are 
:acceptance--->If it has to accept to the terms and agreement etc.
:uniqueness
:singularity
:associated--->If some association is defined and you want automatic validations among the various associations.
:confirm--->eg)confirm password.For example the db will not have 2 fields separately for confirm field but unless this checking is done the db insert or update wont be done.Automatically the confirmation field will be created using "fieldname_confirmation"

:confirm and :acceptance generally doesnt store anything in the database,But can be made to do so.

Exclosion:Accepting values that it wont accept.
Inclusion:Specifying within what it will accept.
:format--->LIke checking the formats for email and stuff.

NILL AND BLANK:
 a=nil
a.nil=true and a.blank=true
a=[]
a.nil=false
a.blank=true
You can also use "if" or "unless" along with validates..

Git:
This is a distributed revision control and version control with an emphasis on speed.If you have heard of subversion this is different from that.In subversion there is a central server from which you get your project make changes and again push it back into it.But git is distributed,and we can download a local copy into our system and make changes this change is applied only into the local copy.Only when you push it it goes into the main copy so that other users can pull it again.While working we can go pull the copy,make it merge and check with the merge conflicts and rectify it and then push it back.
Uses function like "clone" to make a local copy.Even im not sure of this but it is easy if we start working with it i guess.

Slim:
This is the simplified form of haml with no strict indentation issue.Read on to understand that.Haml is nothing but HTML substitute for erb.
Problem with Html:DRY-repeating yourself.
Solution:
HAML
Open and close tags are avoided in this.
<p id="qq">
Hello
</p>

becomes either
%p#qq

Hello

or
%p{id=>"qq"}

Hello

Indentation matters in HAML.Two space or a tab represents nested loops.The second method is better among the above because when the attribute "qq" has to change with runtime returning hashes are better.
->THis reduces code size and doesnt repeat unnecessarily.
->Each code in HAML is converted to HTML,so there is a very little time lag.
-->There are gems lik HAMLtohtml and vice versa to convert between them

SAAS:
This is simpler form of HAML.But this allows inheritance in the classes of the css scripts.

Monday, 27 August 2012

More on Rails!!

Rest:Representational State transfer.This is associated with resources.
What is a resource??Anything that is an entity and also allows and implemetnts Crud and index method.
What is a model??  Anything that interacts with a database is a model.In rails you need not create your database,nor establish access from the scratch.All this is automatically done by the ORM-object relation mapper.

What does an ORM do??It's job is to connect to the database.The attributes are mapped to the columns of the database and the classes are mapped towards the tables in databases.The objects of the classes are mapped to the records of the database.In the tables used in rails the foreign key and the primary key are not used to create the relationships.Instead it is abstracted and relationships are created by the means Associations in OOPS.

Some of the associations are-->has_one
-->has_many
-->has_and -belongs to many
-->belongs+to
In cases where you map 2 tables in a many-many relationship then you have to include an intermediate table to it.The intermediate tables will contain the id's of both the columns.We do not add a seperate id column to this because it is not actually necessary.When you make associations certain dynamic methods are created during the runtime,which is an instance of ruby programming.For ex if user and groups are associated then the methods such as "user.groups" and group.user are created.Assocaition in rails makes it very simpler to  use.

ActiveModel and ActiveRecord:
                         When you create a class,the model class inherits from the ActiveRecord.Active record allows you to access the db records,manipulate it and retrieve it and to perform the other logic necessary.It wraps a table inside an object.The mapping of the objects to rows,attributes to columns etc are done via this.When a new object is created a new row is creates.For instance
part=new Part
part.name="rr"
part.type="qq"
part.save
 will do
insert into part values("1","rr","qq");

Similarly it can also be used to query a database.

What is the ActiveModel then??!.It is the behaviour which allows the ruby objects to act like its active records,by adding validations,callbacks,naming conventions etc.
Activemodel doesnt relate to the tables in the database.

Consider a shopping cart table it can also be put directly in the payment table and paid status can be put to false,but it is a better practice to put it in a seperate table cos only then the dynamic methods like user.shop_cart can be accessed easily else we have to write queries checking for the required records.Also test classes are made simpler.

Callbacks in ActiveRecords:
This is an action performed directly after a DB action.Like a callback is called soon after an object is saved or before that.There are various such callbacks.After_initialize is another important callback.Callbacks are similar to triggers.To enable the proper working of callbacks Hooks are introduced.
To create A hook

create s_hook<ActiveRecord::Hook::Base
   Callbacks helps you in not  writing too much into the model and messing it up.Instead you can put it in the callbacks.When there are large number of callbacks then put it together into a observer.There are certain actions like "update_all"  which will not directly trigger the validations,must use such actions with great care.

Db:
schema.rb locks your db schema while executing.At each migration schema.rb is updated.
For Mongo db like db there is no Db.In such ORM's there is no migration associated with it,so no locking of schemas.

You can either inherit from Active_Record or include its modules.Which is better??When you inherit you are including a lot  of unwanted code.So it is better you include and use the necessary modules as necessary.

Now we will move on to actionpacks which contains Actionview and actionController.
ActionController is thr first to get hit when an request is sent.
What is applicationController??It contains the general settings,like
-->protect_from_forgery for the entire application
-->If signed in go to one page or the other page.
All other controllers are inherited from the application  controller.

Now we know what the application controller does ,so what does a action controller do>>
-->It has ability to call and use the actions
-->Enables code abstraction and so methods can be called as actions.

certain actions in a controller can also be made as a private action .But how will you cal them??Yes it can be called via another method.ie some other action can call this action.
But where exactly do we use private methods in a controller???I am yet to find the answer to this question,will come back with an answer very soon..

Yeahh and so there are many instances where you use private methods in a  controller.Such as if there are subsequent actions that should be done in some other database tables when some db action occurs it can be done in  private methods in a controller.But be sure that the subsequent db action you do is accessed only by self.

If you want to change from the actual form to some other form ,the flow is iven in your controller.You give it as
   render :action=>status
where status is the new view file name.

Render and Redirect_to:
     Render is only used to redirect to some other form.But when you give redirect you go to some other view,but the control goes to the controller and the model before rendreing this view.

Partials:
   Bunch of HTML code for reuse.
   Start s with an "_".

Do you find any instance in rails where you can easily see the block concept implemented.Yes in the layouts the html files basic layout will be given and in the body part the "yield" will be called and this part is given in the various views files.


Sunday, 26 August 2012

Ruby on Rails! Part 2!!

Rails migration:
    Rails migration enables you to do the following.
-->If one person makes a change all the other person needs to do is to just update it and run in a team of developers.
-->When working with multiple systems migrations help in synchronization.
Rails migrations does the following things,
-->create table,drop table ,rename table
-->Add column,delete column,change column ,rename column
-->Add index and remove index extra.
They also support all the basic data types.
  --> Convenient way to alter your database in a structured and an organised manner.
-->For each an every alteration you do to a database,in terms of creation and updation it stores as an unique migration in db/migrate.
-->The name of the migration is based on the timestamp ending with the class name.If you want to change the class name chamge the name of the model else you will get an error saying "No class found".You can also rollback databases whenever you want to undo any new changes that you have created.


Creating the migrations:
It will be done directly on scaffolding.Other way to create is

               ruby script/generate migration table_name
You should use lower case for the table-name that is the rails paradigm.This will create a file in the db/migrate directory which has the structure of the table necessary.
Running the migration:
run db:migrate
As we create migrations we should also write code to rollback to its  
Scaffolding:
-->Enables us to find how the rails exactly works.
-->Quick code to demonstrate and get feedback on rails.
If you are using scaffolding to create a rails application all your work will become very easier.
If you dont use scaffolding you have to create the project,its model,its view and controller,the routing paths,the database ,you have to populate them etc.In using scaffolding all are automatically created .
All the CRUD functions,Create,Delete,Update and Retrieve functions are directly inserted into the controller and doesnt need to be manually added.

Configuring database.yml file :
     This is a very sensitive file.This displays the 3 different environment it offers and the various databases it uses along with the settings and the details.The username and the password for each of the db is also mentioned here.The spaces in this should be given carefully .Any extra space or error will not let you run the create db cmd like
   rake db:create
The above will give an error  "Rake aborted"

The console:
This can be accessed using the rails.console command.
The rails server is run using the "rails.server "command.

Configuring :
The config folder has all the configuration settings of the project.The routs file in that is used to specify where the control is to be redirectd.
What are helpers??
They are used when you have to do some small logic computation relating to the view.For example to get the full name of an user by the concatenating operator.The concatenation is done with the help of a helper.Only the view can access the helper methods.The helper methods are put in a module.The model functions can be accessed using the helpers but not directly.The objects are passed as arguments to the helper by the views,so that the helper can access it.

Simple start with Rails:
After knowing the few of the above basics i started creating a simple rails application using the below link
http://guides.rubyonrails.org/getting_started.html


Ruby Now on Rails!! Intro !

Rails Introduction:
-->Web application development framework written in ruby.
-->Less code can accomplish more than what other programming languages can do.
-->If we use it the right way it is the best,else if u try to bring the old programming practices into it ,it will end up as a big mess.
-->It is an open source framework for developing database backed web application.
-->No compilation phase is required.

Strength of Rails:
-->Metaprogramming : Other frameworks use extensive code generation from scratch. Metaprogramming techniques use programs to write programs. Ruby is one of the best languages for metaprogramming, and Rails uses this capability well.
-->Active Records:Rails have active record framework which saves objects to databases.
-->Convention over Configuration:No need of writing much configuration.If u follow the naming syntax properly,configuration is not necessary.
-->Scaffolding:You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together.
-->Built in testing:Rails creates simple automated tests you can then extend. Rails also provides supporting code called harnesses and fixtures that make test cases easier to write and run.
-->Three environments:Rails provide three different environments,one for production then one for development and testing.There is a fresh database for testing for every test run.

Installing Rails:
1)First Ruby has to be installed.Then install the ruby gems using the command..
               sudo install rubygems
2)Then install the rails gem using
               sudo  gem  install rails--include-dependencies
Updating Rails:
Give
                rails update
Installation verification:
Give "rails demo".A demo project is created.Then give it as "http://localhost:3000".It should give the Welcome aboard or congratulations message.

Model View Controller Pattern:Model stands for all the business logic in the application involving the database.This subsystem is implemented in ActiveRecord library which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables, and so on.Controller is what controls the flow.This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord and ActionView.And view is how the data is displayed on the screen.This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.The request is first sent to the controller and it redirects to the corresponding model which is then displayed on the screen.

The Architecture:
Rails Framework

Directory Structure:
          You can access the directory structure of the demo project that  you created by using
                        C:\ruby\> cd demo

              C:\ruby\demo> dir

The models views and the controllers exist in the app folder in the structure.The config file has the route file which is used for routing r redirecting the file.This is the directory structure:
demo/
..../app
......../controller
......../helpers
......../models
......../views
............../layouts
..../components
..../config
..../db
..../doc
..../lib
..../log
..../public
..../script
..../test
..../tmp
..../vendor
README
Rakefile



Tuesday, 14 August 2012

What else in Ruby??? !!

Monkey patching:
      You have so many functions which are inbuilt in Ruby.This language is so flexible and lets you go and edit the functions for a particular program so that it can act as u want it to perform.This is called as monkey patching.This considerably increases the flexibility of Ruby ,which when over engineered may lead to many inconsistencies.

Array manipulations:
   You can change the way .each function executes by

class Array
def each
     puts "before printing"
     yield(self)
     puts "After printing"
end
end


a1=[1,2,3]
a1.each{|q| puts q}

Output:
before printing
1
2
3
After printing

This is just a simple manipulation ,you can manipulate it to do anything you prefer to.Similar manipulations can be done to Ranges to using the functions available to ranges.

Scope:
      There are different scopes available in Ruby.All methods are public by default.There are other access specifiers like protected,private etc.Both private and public are almost the same.The other details regarding the scope are already mentioned in the relative sections in the previous posts.

Iterators In Ruby:
  Iterators are something which is used to traverse through an array again and again repeatedly.For String class we have iterators like "each_byte" to traverse char by char and "each_line" to traverse between the different lines.For different classes different set of methods are provided.In low level lang like c while iterating  the string you should check for the termination char to give it as a condition but this doesnt require any internal knowledge of the atorage.

a.each{|q| puts q if  q<5}

Attributes:
I have already specified about the accessors that are used for accessing ruby attributes from outside the class.You can either use the predefined one or you can define your own attribute accessors.Both methods are specified in my previous posts.

Exception Handling:
Exception handler is a group of code that is executed when something goes not as expected.When an exception occurs it raises an exception which breaks the normal flow of operations.This exception is rescued by "rescue " and is handled.Any exception raised is an instance of class "Exception"

class exc_test
def div
x=0
raise a=b/x
rescue
puts "im rescued"

ensure

puts "I was not let go"
end

end

The "ensure" is like finally" in java,"raise" is like throw,and "rescue" is like catch.
If all rescues fail "ensure" will catch the exception..

You can also create other exceptions of your own which inherits from Exception class.

class Myownexception<Exception


end

e1=Myownexception.new
raise MyownException

rescue Myownexception=>w
puts "im caught by my rescuer"
end

raise 4/0
 rescue
puts "im rescued by zerodiverror"
end

Standard Library functions: 
         There are many inbuilt functions which are included together in a library which can be required and included and the methods can be used.Whenever you want specific methods check the ruby documentations and use it.

SCalars Date and TIme:
     Date can be identified using  Time class..The following example gives you a gist.

time = Time.new

# Components of a Time
puts "Current Time : " + time.inspect
puts time.year    # => Year of the date 
puts time.month   # => Month of the date (1 to 12)
puts time.day     # => Day of the date (1 to 31 )
puts time.wday    # => 0: Day of week: 0 is Sunday
puts time.yday    # => 365: Day of year
puts time.hour    # => 23: 24-hour clock
puts time.min     # => 59
puts time.sec     # => 59
puts time.usec    # => 999999: microseconds
puts time.zone    # => "UTC": timezone name
 
 
Instance_eval and class_eval: 
Instance_eval has 2 different uses
1)Setting and getting the instance variables.

object_name.instance_eval do
puts @geek
end
2)It is used to define class methods
 
classname.instance_eval do
def who
//class methods content
end
 
puts classname.who 

Class_eval:

1)setting and getting class variables

puts classname.class_eval("@geek")
classname.class_eval do
 @@geek="fds"
end

2)Defining instance methods
classname.class_eval do
//instance methods
end

Another method is used to set and get variables

object.instance_variable_get(geek)
object.instance_variable_set(geek="rona")










Monday, 13 August 2012

Few Other Ruby examples!:)

In case you have a function inside another function then when you call the uter function the inner function is defined.Again when you call the inner function it gets invoked.If both the inner and outer function has the same name,then all calls other than the first call points to the second inner function.


def one
    puts "one"
    def one
        puts "two"
    end
end

one
one
one
op:one two two two....

This is another function with define_method inside a "def" and allows dynamic multiplication..

class Mul
def self.fn(other)
    define_method "mul_#{other}" do
         puts 5*other
    end
end
end
val=3

m=Mul.new
Mul::fn(3)----------------------**
puts "before"
m.mul_3--------------------------*
puts "after"

op:
before
15
after

In the above example you would have noted that though it is dynamic you would hve to specify the changed value in * and **.To avoid this you create all instance of function from mul_1 to mul_10..Check the foll pgm ...



class Multiplier
  def self.fn(n)
    define_method "mul_#{n}" do |x|
    puts  x*n
  end
end
  
for i in (1..10)
fn(i)
end

end


m = Multiplier.new


 m.mul_3(5)----*
 m.mul_7(5)
Here in each case u need to call only once.
There is another important function "method_missing" that is called when undefined methods are called.You can override this method to perform  the requires task you want.Now we will override the method_missing function and perform the same above task.

class Check

def method_missing(name,*args)
    puts "im n missing method function"
    self.class.send(:define_method ,name) do |*args|
        puts "im inside define_method"
        #name1=name[name.length-1]
         name1=name.to_s
         
          name2=name1.split("_")
           value=name2[1]         
          return value.to_i*args[0]
          

    end

self.send(name,*args)
end

end

c1=Check.new
puts c1.mul_4(10)
puts c1.mul_4(6)
puts c1.mul_2(60)

In the above method we have a great advantage.You define only the function that is called.Not all the function as in the previous case.

Inject Function:
     puts   [1, 2, 3, 4].inject { |result,a|; result +a }
This returns the sum of the values of the array.


Defining and Using the attr-accessor:

class Animal
  


    define_method attr_name do
      instance_variable_get("@#{attr_name}")
    end
    
    define_method "#{attr_name}=" do |new_val|
      instance_variable_set("@#{attr_name}", new_val)
    end
    
  end
  my_attr_accessor :name
  my_attr_accessor :age
end

a = Animal.new
a.name = "Rona"
a.age=100
puts a.name
puts a.age



op.:
Rona
100


Code for sending mail using "gmail" in ruby:


require 'net/smtp'

YourDomain = 'smtp.gmail.com'
YourAccountName = 'from####@gmail.com'
YourPassword = '######'

FromAddress = 'from###@gmail.com'
ToAddress = 'to####@gmail.com'


@msg = "Subject: Hi There!\nThis is the body.  Tested on ruby 1.8.7"

smtp = Net::SMTP.new 'smtp.gmail.com', 587
smtp.enable_starttls
smtp.start(YourDomain, YourAccountName, YourPassword, :login) do
  smtp.send_message(@msg, FromAddress, ToAddress)
  puts 'Mail sent'
end

This code facilitates you to first login and authenticate your account and the n send your mail.You have to install the gem "tlsmail" for this to execute.
-->587 is the post number through which the connection will be established.

What is aliasing??How is it done??
   Alias_ method is used for aliasing functions.At a particular instant when alias_method function is encountered the new function points to the old function at that instant.For instance consider the example..
Syntax: alias_method :newfn :oldfn

You can 

class Alias_test
def alias1
    puts "This is the first function"
end
alias-method :alias_dup :alias1

def alias1
    puts "This is the second function"
end
end


Alias_test a1
a1.alias_dup
a1.alias1

Output:
This is first function
This is second function