Friday, 14 December 2012

Ruby on Rails with HAML


Create a new app using
$ rails new demo_app_haml
then, bundle update( as usual as we do in normal app)
include "gem haml" to your gem file.
and then update your bundle.
clone this:     git clone git://github.com/psynix/rails3_haml_scaffold_generator.git lib/generators/haml     which will configure Rails 3 to use HAML generators instead of ERB  when we run any sacffold or controller because it is annoying to constantly remove  .erb files, and or edit them into HAML syntax.
hmmm... not yet done, we need a small configuration setup that will assist in haml file generation. 
Goto Confing/application.rb add 
config.generators do |g|
     g.template_engine :haml
end
Finally run your scaffold.. that it here we have all the erb files in haml...

 

Sunday, 9 December 2012

Adjusting Heroku Timezone


Adjusting Heroku Timezone
Changing the timezone on the Heroku Cedar stack can be done in a few easy steps.
Grab your the appropriate zone name string from here
In your console/shell:

$ heroku config:add TZ=EST
Application will restart automatically after this action.

To test it out:
console/shell:
$ heroku run console
$ Time.now

Friday, 7 December 2012

Best practice for coder(Rails)


CONTROLLER-

1.Keep the controllers skinny - they should only retrieve data for the view layer and shouldn't contain any business logic (all the business logic should naturally reside in the model).

2.Each controller action should (ideally) invoke only one method other than an initial find or new.

3.Share no more than two instance variables between a controller and a view.




ACTIVE RECORD:

1.Avoid altering ActiveRecord defaults (table names, primary key, etc) unless you have a very good reason (like a database that's not under your control).

2.Group macro-style methods (has_many, validates, etc) in the beginning of the class definition.

3.Prefer has_many :through to has_and_belongs_to_many. Using has_many :through allows additional attributes and validations on the join model.

4.Beware of the behavior of the update_attribute method. It doesn't run the model validations (unlike update_attributes) and could easily corrupt the model state.


Don't Repeat Yourself
                         I'm sure most of you have heard of the DRY principle. It is something Rails has taken to heart, and I'm very glad it has. By not repeating yourself you can freely change something in one area of the program without worrying if you need to make the same change in another area. Not only that, but keeping the code DRY usually leads to better design.

Sometimes it is difficult to find duplication in your code. If you find yourself making a similar change in multiple places, you should first remove this duplication so you only need to make the change in one place.

This principle should not only be followed in code, but in your database and other areas as well. If you are repeating logic or data in the database, consider changing the design so it is not repeated.

That said, there are times when repeated data is good. For example, if you are building a cart system, the price for the items in the cart should be stored in a separate field than the price for the product. This allows you to change the price of the product without effecting all previous orders.


Stick to the Conventions
               Another extremely important practice taken up by the Rails community: stick to the conventions. From naming variables to structuring files, there are conventions on how to do these things in Rails. If you are unsure of the conventions, check out a Rails book or tutorial - most of them stick to the conventions.

The advantages of sticking to conventions are almost too numerous to count. In fact, it deserves its own article.

Optimize Later
              Performance is a major concern for many people switching to Rails, and rightly so. It is true that Rails is generally slower than other web frameworks. However, it is very scalable, so do not worry about it at the beginning. If you are a large corporation that needs to handle thousands of requests per second, then you may have something to be concerned about, but for the majority of us performance does not need to be considered until near the completion of the application.

Any optimization done early requires guessing. Instead you should wait until you know where the bottlenecks are. Optimizing usually requires extra/complex code, and you should keep the code as clean and simple as possible. Therefore, only optimize where necessary. Also, any performance testing should be done in the production environment, as this adds some optimizations which are usually turned off in the development environment.

Above all else, don't let fear of poor performance inhibit you from making good design decisions! There are usually good ways to optimize while still keeping the good design, but these ways are hard to see unless you have a good design already in place. In short, don't worry about performance while designing.

Humans First
              Code for humans first, computers second. In other words, make the code as readable as you can. No, I'm not talking about cluttering it with comments. Most code should be understandable without comments.

How do you make the code more readable without comments? Rename variables, move code into classes/methods, etc. Try to give variables and methods concise, yet descriptive names. Do not abbreviate the names unless the abbreviation is very common.

Test Driven Development
              You've heard it said: "Rails makes testing easy, so you don't have any excuses not to do it.". Well, in my opinion, testing is never easy - it is just easier in Rails.

Seriously, if you have not tried test driven development, give it a go. Automated tests are a godsend! I find myself rarely going to the web browser anymore to test things out. I just know it works because all of the tests pass. I wouldn't dare code a mildly complex application without testing anymore. It will take some time to get used to testing, but the benefits are far worth it.

Refactoring
                This is my favorite best practice, and for good reason. Refactoring ties all of the things in this list together. Simply put, if you want to become a better programming, learn Refactoring. Normally the first time you write a piece of code, it is messy. Whatever you do, don't leave the messy code as is. Even if it works correctly, it will be a headache to maintain. You should take some time to clean up the code, make it readable, and improve the design.

For more reference: http://www.sitepoint.com/10-ruby-on-rails-best-practices/

Customize Devise Validations


Keep the sweet Devise format validations, and customize devise validations by rolling your own

First, remove the :validatable argument from the devise method

devise :database_authenticatable, :token_authenticatable

Then, you’ll need to implement your own validations. Depending on your intentions, either include or exclude validates_presence_of :email
$ validates_uniqueness_of :email, :case_sensitive => false, :allow_blank => true, :if => :email_changed?
$ validates_format_of :email, :with => Devise.email_regexp, :allow_blank => true, :if => :email_changed? 
$ validates_presence_of :password, :on=>:create validates_confirmation_of :password, :on=>:create
$ validates_length_of :password, :within => Devise.password_length, :allow_blank => true


I know the above looks vaguely familiar… say: what you used to write all the time before Devise kicked in. But look at the devise validatable source – this is all it’s doing anyway.


Also cool: use the Devise.email_regexp and Devise.password_length to get good email validations.
          This post was valid with Devise 1.4.6 and Rails 2.3/3.0/3.1.

Monday, 3 December 2012

Rails Date Formats – strftime


Rails Date Formats – strftime

StrFTime Format Codes for Ruby on Rails
Year
%Y year with century 2007
%y year without century 07
%C century number (year divided by 100) 20

Month
%B full month name January
%b abbreviated month name Jan
%h same as %b Jan
%m month as number (01-12)

Week
%U week number of the year, Sunday as first day of week (00-53)
%W week number of the year, Monday as first day of week (00-53)

Day
%A full weekday name Wednesday
%a abbreviated weekday name Wed
%d day of the month (01-31)
%e day of the month, single digits preceded by space ( 1-31)
%j day of the year (001-366)
%w weekday as a number, with 0 representing Sunday (0-6)
%u weekday as a number, with 1 representing Monday (1-7)

Time
%H hour (24-hour clock) (00-23)
%k hour (24-hour clock); single digits preceded by space ( 0-23)
%I hour (12-hour clock) (01-12)
%l hour (12-hour clock); single digits preceded by space ( 1-12)
%M minute (00-59)
%S seconds (00-59)
%p either AM or PM AM
%Z timezone name or abbreviation EDT
%z timezone offset from UTC -0400

Summaries
%D date, same as %m/%d/%y 05/16/07
%v date, same as %e-%b-%Y 16-May-2007
%F date, same as %Y-%m-%d 2007-05-16
%R time, 24 hour notation, same as %H:%M 18:06
%T time, 24 hour notation, same as %H:%M:%S 18:06:15
%r time, am/pm notation, same as %I:%M:%S %p 06:06:15 PM

Formatting
%n newline character
%t tab character
%% percent character

Less common formats
%s number of seconds since the Epoch, UTC
%c national date and time representation
%+ national date and time representation
%x national date representation
%X national time representation
%G year with century, starting on first Monday where week has 4 or more days.
%g year without century, starting on first Monday where week has 4 or more days.
%V week number of the year, starting on first Monday where week has 4 or more days.

Saturday, 1 December 2012

Diff b/w DATE, TIME, DATETIME, TIMESTAMP



DATE only stores a date
TIME only stores a time of day
DATETIME stores both.

difference between DATETIME and TIMESTAMP:
1. DATETIME is formatted as YYYY-MM-DD HH:MM:SS
2. DATETIME Valid ranges go from the year 1000 to the year 9999
3. DATETIME stores every digit in the year, month day, hour, minute and second, it uses up a total of 8 bytes.

Timestamp:
1. TIMESTAMP only stores the number of seconds since 1970-01-01, it uses 4 bytes
2. valid range goes from 1970 to 2038.


In rails:
 Both :timestamp and :datetime will default to DATETIME

Friday, 23 November 2012

Stay Up to Date …(ROR)


Stay Up to Date …

Learning to program well is a never-ending process. That’s why you should subscribe to various blogs and Twitter accounts on the subject. Here’s a list of influential Rails people for you to follow on Twitter:
  • @dhh: The creator of Ruby on Rails. Posts insight on new releases and various tips.
  • @rbates: Producer of Railscasts, posts tips and tricks very often.
  • @rails: The official Ruby on Rails Twitter account. Follow them if you want insight on release dates, and development.
  • @rails_apps: They’re posting new Rails example apps pretty often, pretty useful.
And here are some websites you should subscribe to:
  • Railscasts: A must! Awesome screencasts about Ruby on Rails, best practices, tips, new gems, etc.
  • Asciicasts: If you’re not into watching videos, this site mimics Railscasts’ tutorials in text. It’s not as up-to-date as the first one, but it’s excelent.
  • Nettuts+: While we’re not 100% focused on Ruby and Rails, we’re posting more and more applicable content these days!
  • The Rails Way: Cool blog with various articles and tutorials.
  • Riding Rails: The official Ruby on Rails blog. They don’t post many tips or tutorials, but they announce official releases, so it’s good to read it often.
  • Planet Ruby on Rails: A Ruby on Rails blog aggregator. It’s no as filtered as reading one of the blogs I listed above, but it’s a good resource to check every once in a while.

Tuesday, 6 November 2012

Install RMagick on ubuntu



$ sudo apt-get install libdjvulibre-dev libjpeg-dev libtiff-dev libwmf-dev libmagickcore-dev libmagickwand-dev libmagick++-dev



$ sudo gem install rmagick

Tuesday, 9 October 2012

Sort an array of objects by an attribute



Here is an example to sort an array of (the same kind of) objects by an attribute. Let's say you have an array of User objects that have the attributes 'name'
. First, find all
$ users. @users = User.find(:all)

Now, we have to sort this array by 'name'. Since we don't know if any user used capitals in his name or not, we use 'downcase' to sort without case sensitivity.

A small not. 'sort' returns a new array and leaves the original unchanged. You may want to just reorder the @users array, so use the 'sort!' method. The '!' indicates it's a destructive method. It will overwrite the current @users array with the new sorting. 

$ @users.sort! { |a,b| a.name.downcase <=> b.name.downcase }


Since strings are comparable, this will sort you user objects alphabetically by name.

That's all! :)

Tuesday, 2 October 2012

objects parent and child access

If we have an object profile.

$ x = Profile.all.first
 #<Profile _id: 506a8bc5a788000c6300002f, _type: nil>
to fetch the child details of the object we can have
$ x._children
[#<ProfileKidsType _id: 506a8bc5a788000c6300002e, _type: "ProfileKidsType", fname: "jyothi", lname: "k ", kids_id: "KL295170", nickname: "jyoths", gender: "Female", birthdate: 2012-10-02 00:00:00 UTC, food_allergies: "No", medical_issues: "No", special_needs: "No", other_concerns: "No", organization_memberships: nil>]
so we have the child details, this can have the parent details . so
$ y= x.kids_type
$ y._parent
#<Profile _id: 506a8bc5a788000c6300002f, _type: nil>

y._parent will be the parent details of the child object

here is an example:




Saturday, 29 September 2012

How to kill Skype process in Ubuntu


How to kill Skype process in Ubuntu

The Skype process seems to be immortal when it crashes in Ubuntu. Killing it with “killall skype” does not work. And it’s not a nice process either, because it uses 100% CPU!

Fortunately, there is a way of killing it without restarting your computer. This is how to do it:

$ killall skype -s 9


and you can start skype form terminal using skype -i

Friday, 21 September 2012

Focusing first elemet in the form using jquery



Focusing first element in the form using jQuery

                $("form:not(.filter) :input:visible:enabled:first").focus();

Thursday, 20 September 2012

Installing Ruby on Rails Ubuntu 11.10


Installing Ruby on Rails Ubuntu 11.10 using RVM and Ruby 1.9.2

Follow:
sudo apt-get update
sudo apt-get install build-essential git-core curl libmysqlclient16-dev nodejs
Now let’s install the latest version of RVM using curl:
sudo bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer)
umask g+w
source /etc/profile.d/rvm.sh 
Now you'll need to ask RVM if it needs any more programs and if so you'll need to install them to do this type:
rvm requirements
Two things could happen here if you see the following message saying you need to install 'rvm', ignore this it and restart your terminal, this should fix the problem.
The program 'rvm' is currently not installed.  You can install it by typing:
sudo apt-get install ruby-rvm
You should see something that looks like this after you restart your terminal:
This tells you which packages you need to install using apt-get, just copy and paste the apt-get section under "# ForRuby" and run using the sudo command, this should look something like this:
sudo apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion
Now you just need to give the user account access to the rvm files, you do this with the following command substituting [user] for the user you wish to use
sudo chown -R [user]:[user] /usr/local/rvm
Once you have installed all these packages its time to install Ruby 1.9.2 herself. The following command will installRuby 1.9.2 using the rmv package. However this can take a few minutes (15 in my case) to install so I recommend getting a drink, or my favourite, a pizza :lol: .
rvm install 1.9.2
Once ruby is installed you should set Ruby 1.9.2 as your default Ruby version, to do this enter:
source "/usr/local/rvm/scripts/rvm"
rvm --default use 1.9.2
You can test that Ruby is installed correctly and running at version 1.9.2 by typing
ruby -v

The nice thing about RVM is you can use it to install any version of Ruby and switch between the versions your have installed, to do this just enter "rvm install [Version Number]" then "rvm --default use [Version Number", you can then use "rvm --default use" to change to any installed version.This should output something like "ruby 1.9.2p290.." showing you that version 1.9.2p290 is installed and is now the defaultRuby version.
Now that you have the latest version of ruby installed I’m sure you want to get the latest version of Rails installed, at the time of writing this tutorial that’s Rails 3.1. To installRails we can use GEM which is installed along with RVM and Ruby, to install the latest version of Rails just type, (this can take also take a while):
gem install rails
And that’s it you have now installed RVMRuby 1.9.2 and Rails 3.1 on Ubuntu 11.10 configured to use sqlite3, you can now setup your new Rails package with
rails new [project name]
Just as a final note, If you want to use MySQL instead of sqlite3 you’ll need to enter the following
sudo apt-get install mysql-server
gem install mysql2
rails new [project name] -d mysql

Tuesday, 18 September 2012

Haml important things to remember


How to Convert

Let’s basic ERB that we want to convert.

ERB

<strong><%= item.title %></strong>

Haml

%strong= item.title
In Haml, we write a tag by using the percent sign and then the name of the tag. This works for %strong%div%body%html; any tag you want. Then, after the name of the tag is =, which tells Haml to evaluate Ruby code to the right and then print out the return value as the contents of the tag. Unlike the ERB above, Haml will automatically detect newlines in the return value and format the tag properly.
Simple tags are all well and good, but what about adding attributes to tags?

HTML

<strong class="code" id="message">Hello, World!</strong>

Haml

%strong{:class => "code", :id => "message"} Hello, World!
The attributes are just a standard Ruby hash. The class attribute is “code”, the id attribute is “message”. Notice that in this example, we didn’t use =, so “Hello, World!” is interpreted as a normal string, not Ruby code.
There is a simpler way to define this tag in Haml, since class and id are such common attributes and since most designers (and coders) are familiar with CSS, we can use similar notation to describe this tag.

Haml

%strong.code#message Hello, World!
Not only that, but since div tags are so common, you can leave off the tag definition and have it default to %div.

Haml

.content Hello, World!

HTML

<div class='content'>Hello, World!</div>
Now what about something a little more complicated?

ERB

<div class='item' id='item<%= item.id %>'>
  <%= item.body %>
</div>
Pretty basic. This might be part of a partial or something. Let’s convert it to Haml.

Haml

.item{:id => "item#{item.id}"}= item.body

Now, nesting is taken care of in Haml via whitespace.

ERB

<div id='content'>
  <div class='left column'>
    <h2>Welcome to our site!</h2>
    <p><%= print_information %></p>
  </div>
  <div class="right column">
    <%= render :partial => "sidebar" %>
  </div>
</div>

Haml

#content
  .left.column
    %h2 Welcome to our site!
    %p= print_information
  .right.column
    = render :partial => "sidebar"
Thats it... :)

Thursday, 13 September 2012

Go to top of page using jQuery

This one liner jQuery snippet will force your browser to go to the top of your page:

$('html, body').animate({ scrollTop: 0 }, 0);

If you want to add some smooth scrolling:
$('html, body').animate({ scrollTop: 0 }, 'slow');

Here is the one where i used when he resets, i am making this

%input.btnCancel{:type => "reset", :value => "Reset without saving", :id => "reset"}

 $('#reset').click(function() {
    $('html, body').animate({ scrollTop: 0 }, 0);
    location.reload().scrollTop(0);
  });

Thursday, 30 August 2012

simplest way to comment in rhtml


The simplest way to do this is to define an a comment method in the application_helper.rb:

def comment(&block)
 #block the content
end

And use it in rhtml templates
<% comment do %>
  .. Some HTML
  .. Some ruby scriptlets
<% end %>


How this works:


def x(&block) # x is a 0 param function                                                                
    y(block) # y is a 1 param function (taking one "Proc")                                    
    z(&block) # z is a 0 param function (like x) with the block x received              
end                                                                                                                         



So, if you call z(&block) it's (nearly!!) the same as calling z { yield }: You just pass the block to the next function.

know the controller and action in view



Just write the below code in your  to know current controller name in a view the right path is

<%= controller.controller_name %>
<%= controller.action_name %>

Wednesday, 29 August 2012

Create a New app Using Mongo db



create new repository using this command:

$ rails new <app_name> -T -O

Use the -T -O flags to skip Test::Unit files and Active Record files.

Ex: $ rails new example_mongo -T -O

include this gems in your gem file:


gem "mongoid", "~> 2.2"    
gem "mongo", "~> 1.5.0.rc0"
gem "bson", "~> 1.5.0.rc0"
gem "bson_ext", "~> 1.5.0.rc0"

go to the repository and run $ bundle update command.

then run $ rails g mongoid:config to generate your configuration file.

try to create a table using scaffold

exp: $ rails g scaffold user name:string email:string

Every thing should go fine... That's it..
:)




Mongoid::Paperclip


Mongoid::Paperclip - Making Paperclip play nice with Mongoid 

1st Install Image Magick using

$ sudo apt-get install imagemagick

As the title suggests: Mongoid::Paperclip makes it easy to hook up Paperclip with Mongoid.
This is actually easier and faster to set up than when using Paperclip and the ActiveRecord ORM. This example assumes you are using Ruby on Rails 3 and Bundler. However it doesn't require either.

Setting it up

Simply define the mongoid-paperclip gem inside your Gemfile. Additionally, you can define the aws-s3 gem if you want to upload your files to Amazon S3. You do not need to explicitly define the paperclip gem itself, since this is handled bymongoid-paperclip.
Rails.root/Gemfile - Just define the following:
gem "mongoid-paperclip", :require => "mongoid_paperclip"
gem "aws-s3",            :require => "aws/s3"
Next let's assume we have a User model and we want to allow our users to upload an avatar.
Rails.root/app/models/user.rb - include the Mongoid::Paperclip module and invoke the provided class method
class User
  include Mongoid::Document
  include Mongoid::Paperclip

  has_mongoid_attached_file :avatar
end

That's it

That's all you have to do. Users can now upload avatars. Unlike ActiveRecord, Mongoid doesn't use migrations, so we don't need to define the Paperclip columns in a separate file. Invoking the has_mongoid_attached_file method will automatically define the necessary :avatar fields for you in the background.

include  :html => { :multipart => true } for form.