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