Friday, 29 June 2012

hash syntax change in ruby 1.9

Hi,

In ruby 1.9 hash syntax has been changed. Use the new syntax to over come the problem while upgrading some gems or plugins to future versions.

# Ruby 1.8 Syntax
{:name => 'uma mahesh', 'phone' => '9866439593'}
# Ruby 1.9 syntax
{name: 'uma mahesh', 'phone': '9866439593'}


hash keys should accessed with symbols as below

profile = {:name => 'uma mahesh', 'phone' => '9866439593'}

profile['name'] # => nil

profile[:name] => 'uma mahesh'

The new syntax mimics JSON which is important for Ruby, or at least Rails, developers as JavaScript is one of the languages we’ll switch to more frequently.


Its is similarity to JavaScript's object notation, and looks a bit like JSON



Thank You,
Uma Mahesh.

creating indexes for all database tables on fly in rails

Hi,

Indexing plays a major role in database query optimisation. So it is suggested to have index for foreign_key columns.

Coming to rails migrations, our migration will not create indexes for the columns with foreign keys. Where you need to create manually those indexes.


Normal migration will be as below

class CreateArticle < ActiveRecord::Migration
  def self.up
    create_table "articles" do |t|
      t.string :content
      t.integer :post_id
      t.integer :user_id
    end
  end

  def self.down
    drop_table "articles"
  end
end


Inorder to add indexes, add the indexes as below:

class CreateArticle < ActiveRecord::Migration
  def self.up
    create_table "articles" do |t|
     t.string :content
     t.integer :post_id
     t.integer :user_id
    end

    add_index :articles, :post_id
    add_index :articles, :user_id
  end

  def self.down
    drop_table "articles"
  end
end


In some cases we may not sure which column need to index, In that case I strongly recommend to use the below gem which creates indexes for all the foreign_key columns on fly by running a simple command.

gem rails_indexes(A rake task to track down missing database indexes.) https://github.com/umamahesh/rails_indexes

usage:

add the gem to your gem file.

gem "rails_indexes"

> bundle install

> rake db:index_migration

Display a migration for adding/removing all necessary indexes based on associations:


Thank You,
Uma Mahesh.

postgres_ext gem native postgres datatypes in rails

Hi,

We are using different datatypes depending on the requirement of data that is being saved in database.

Coming to postgres database, it supports many datatypes and we can't use all those datatypes directly in rails.

To over come this problem, we had a new gem postgres_ext


postgres_ext supports 3.2 and above version of rails.

postgres_ext adds migration and schema.rb support for the following PostgresSQL type:

    INET
    CIDR
    MACADDR
    UUID
    Arrays


example:

create_table :users do |t|
  t.inet :myip


  t.cidr :mysubip


  t.macaddr :ip_address


  t.uuid :member_id

  t.integer :friend_ids, :array => true

end


postgres_ext converts INET and CIDR values to IPAddr instances.

example:

create_table :inet_examples do |t|
  t.inet :ip_address
end

class MyExample < ActiveRecord::Base
end

my_example = MyExample.new
my_example.ip_address = '127.0.0.0/34'
my_example.ip_address
# => #<IPAddr: IPv4:127.0.0.0/255.255.255.0>
my_example.save

my_example_u = MyExample.first
my_example_u.ip_address

# => #<IPAddr: IPv4:127.0.0.0/255.255.255.0>



array type:

example;

create_table :people do |t|
  t.integer :favorite_numbers, :array => true
end

class User < ActiveRecord::Base
end

user = User.new
user.like_numbers = [1,2,3]
user.flike_numbers
# => [1,2,3]
user.save

user_2 = user.first
user_2.like_numbers
# => [1,2,3]
user_2.like_numbers.first.class
# => Fixnum



here is the git url: https://github.com/umamahesh/pg_array_parser

Thank You,
Uma Mahesh.

Thursday, 28 June 2012

minimum things that a rails developer should have


This what I think a middle rails developer should have :


1. 2-3 RoR projects experience long enough to find design flaw in the implementation
2. Fluent with one test engine (test-unit, rspec, minitest)
3. Knowing minimal gems (authentication, pagination)
4. Writing idiomatic ruby code
5. Knowing at least 1 thing he doesn't like in RoR

The above points are said by martin one of my linkedin friend.

Thank You,
Uma Mahesh.

David Heinemeier Hansson rails creator

David Heinemeier Hansson rails creator

From Wikipedia, the free encyclopedia

David Heinemeier Hansson (known to the Ruby and ALMS communities as DHH) is a Danish programmer and the creator of the popular Ruby on Rails web development framework and the Instiki wiki. He is also a partner at the web-based software development firm 37signals.

Hansson co-wrote Agile Web Development with Rails with Dave Thomas in 2005 as part of The Facets of Ruby Series. He also co-wrote and Getting Real and Rework with Jason Fried.

Programming
In 1999 Hansson founded and built a Danish online gaming news website and community called Daily Rush, which he ran until 2001..

After attracting the attention of Jason Fried by offering him help with PHP coding, Hansson was hired by Fried to build a web-based project management tool, which ultimately became 37signals' Basecamp Software as a Service product.

To aid the development process, Hansson used the then-obscure Ruby programming language to develop a custom web framework. The web framework he created was later released separately from the project management tool as the open source project Ruby On Rails. In 2005 he was recognized by Google and O'Reilly with the Hacker of the Year award for his creation of Ruby on Rails.


facebook page : http://www.facebook.com/pages/David-Heinemeier-Hansson

official website : http://david.heinemeierhansson.com/

twitter page : https://twitter.com/#!/dhh


Thank You,
Uma Mahesh.

famous people saying about rails

Yukihiro Matsumoto, Creator of Ruby
“Rails is the killer app for Ruby.”

Evan Williams founder of Twitter
“After researching the market, Ruby on Rails stood out as the best choice. We have been very happy with that decision. We will continue building on Rails and consider it a key business advantage.”

Tim O'Reilly, Founder of O'Reilly Media
“Ruby on Rails is a breakthrough in lowering the barriers of entry to programming. Powerful web applications that formerly might have taken weeks or months to develop can be produced in a matter of days.”

James Duncan Davidson, Creator of Tomcat and Ant
“Rails is the most well thought-out web development framework I’ve ever used. And that’s in a decade of doing web applications for a living. I’ve built my own frameworks, helped develop the Servlet API, and have created more than a few web servers from scratch. Nobody has done it like this before.”

Thank You,
Uma Mahesh.

Friday, 22 June 2012

ssh connection refused error

Hi,

I am trying to connect remote system with ssh and I have faced below issue. 

ssh umamahesh@123.45.67.891

ssh: connect to host 123.45.67.891 port 22: Connection refused


Here are few things that need to check while connecting to remote system.

1. Does remote system has ssh enables ?

run the below command
> 'sudo /etc/init.d/ssh start'

Here is the error that may rise when there was no ssh installed

sudo: /etc/init.d/ssh: command not found

so you need to install ssh first in your remote system to accept the ssh connections.

run the below command to install ssh

> sudo apt-get install openssh-server openssh-client

Now try the below command

> sudo /etc/init.d/ssh start

Now it should work as ssh installed.

ThanK you,
Uma Mahesh.

Wednesday, 20 June 2012

difference between update_attribute and update_attributes

Hi,

update_attribute and update_attributes both are used to update the object without having explicitly Active Record to update.

The main difference between them is update_attribute will not call validations and callbacks, it will skip validations and callbacks while updating the record.

Let me explain clearly

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2614
       def update_attribute(name, value)
         send(name.to_s + '=', value)
         save(false)
       end


In the above parameter that was passing for the save is false. i.e  save(perform_validation = false)). So it will skip the validations and there by callbacks.


Coming to update_attributes

      # File vendor/rails/activerecord/lib/active_record/base.rb, line 2621
       def update_attributes(attributes)
         self.attributes = attributes
         save
       end

In the above case we are not passing any parameter for the save. So it will be default 'true'. So it will call the validations.

Important point at here is, we should choose update_attribute mainly for updating Boolean column datatypes, where it is not required that much validations.

Here is the syntax that should be used for update_attribute

@user.update_attribute(:status, true)

The main goal of update_attribute is to bypass the stuff and make the update operation fast.




Thank You,
Uma Mahesh.

Tuesday, 19 June 2012

Truncate a string without cuting in middle of the word

Hi,

While displaying come content in the web page, we may required to truncate the text to some extent i.e limiting the text certain length.

In past I sued to do as below

> text[0..100]

It used to truncate the text to 100 characters length but the word at the last one will be cut.

rails provides a good helper method for truncate the string without cutting words.

truncate(description, :length => length, :separator => ' ')

This will be very useful while truncate the string.


Thank You,
Uma Mahesh.

Tuesday, 12 June 2012

Open source ecommerce ruby on rails application - ror-e.com

Hi,

I came to see a new open-source e-commerce ruby on rails application was launched recently. Let me share my views on it.

ror-e.com http://www.ror-e.com/ is a complete e-commerce platform written in ruby on rails on latest version of rasil3.

Its completely open-source and can easily customised to your needs depending on your requirements.

Its is completely different from other rails application with e-commerce functionality which uses engines and other framework.

Here are the few features of it:

ROR e-commerce is a Rails 3 application with the intent to allow developers to create an e-commerce solution easily. This solution includes, an Admin for Purchase Orders, Product creation, Shipments, Fulfilment and creating Orders. There is a minimal customer facing shopping cart understanding that this will be customised. The cart allows you to track your customers cart history and includes a double entry accounting system.


The project has solr searching, compass and blueprint for CSS and uses jQuery. The gem list is quite large and the project still has a large wish list but it is the most complete solution for Rails today and it will only get better.

Please use Ruby 1.9.2 and enjoy Rails 3.1.1.

Here is the link for complete documentation : http://www.ror-e.com/doc/file.README.html

websites that have been developed using ror-ecommerce
1) https://tonx.org
2) https://secure.archerandreed.com


I will start working on it and will post my experience on this.

Thank You,
Uma Mahesh.

Text Editor for rails application with jquery

Hi,

Recently I came to see Jquery text editor markitup which is easy to use.

I have worked on many editors in ruby on rails application like TinyMCE, simple editor. They provide good features in rails application. But all these are rails application dependent.

So I suggest you to use Jquery markitup editor insode your rails application.

You can get complete information and demo of the editors at the URL: http://markitup.jaysalvat.com/

Thank You,
Uma Mahesh.
 

Monday, 11 June 2012

command to get database dump file from postgres database

Hi,

Here is the command to get database dump in postgres

sudo -H -u postgres pg_dump <databasename> > <dumfilename>

Thank You,
Uma Mahesh

Sunday, 10 June 2012

Integrating mailchimp in ruby on rails application

Hi,


MailChimp provides Free email marketing service. You can simply design your email template with nice tools provided by mailchimp and can easily send to list of members that were maintained in the mailchimp list directory.

MailChimp provides many features, For now I am just concentrating on the creating user record in the MailChimp List.

Inorder to Implement mailChimp in ruby on rails application, we have nice gem hominid(https://github.com/terra-firma/hominid). Hominid provides required methods to connect to MailChimp api.



Lets start by creating an account in mailchimp by registering as a free user. Once you logged in to MailChimp You can get the required api access details from the 'API Keys & Authorized Apps' section under the 'Account' tab. You can get api key from that section.


--------------------------

Add the gem to your gem file.
> gem "hominid"

---------------------------
Configure the mailchimp credentails(api) details in yml file under config/mail_chimp.yml

common: &default_settings
  api_key: "asfgtc4a6cd9917tyuhb752867c23eb5-er5"
  subscriber_list: "g67b678706"

development:
  <<: *default_settings
test:
  <<: *default_settings
demo:
  <<: *default_settings
staging:
  <<: *default_settings

production:
  api_key: "xxxxxxxxxxxxxxxxxxxxxxx"
  subscriber_list: "xxxxxxxxxx"

------------------------------

Load the configuratiosn in initializer file in config/initializers/mail_chimp.rb

MAIL_CHIMP = YAML.load_file("#{Rails.root}/config/mail_chimp.yml")


--------------------------------

Craete a class with Mailchimp under model folder models/mail_chimp.rb

class MailChimp
  include Hominid

  def self.add_user(user)
    h = Hominid::API.new(MAIL_CHIMP[Rails.env]['api_key'])
    h.list_subscribe(MAIL_CHIMP[Rails.env]['subscriber_list'], user.email, {'FNAME' => user.first_name, 'LNAME' => user.last_name}, 'html', false, true, true, false)
  end

  def self.unsubscribe_user(user)
    h = Hominid::API.new(MAIL_CHIMP[Rails.env]['api_key'])
    h.list_unsubscribe(MAIL_CHIMP[Rails.env]['subscriber_list'], user.email)
  end

end

------------------------------
You need to call the above methods in your user class after creating the user by using call back 'after_create' in models/user.rb

 after_create :create_user_record_in_mailchimp

def create_user_record_in_mailchimp
MailChimp.add_user(self)
end

----------------------------------

The above explanation helps you to create user record in mailchimp list while user creates in the rails application.


Thank You,
Uma Mahesh.

Unix Command to Copy files from remote computer to local computer


Hi,

Here is the command to copy file from remote computer to local system through SSH shell.

> rcp -r root@12.345.67.890:/home/umamahesh/railsknowledge/ local_folder

Above command will connect to IP: 12.345.67.890 as root user and copy the files from  railsknowledge to local folder 'local_folder'

When you run the above command you will be prompted to submit the password. Where you need to submit the root password.

Thank You,
Uma Mahesh.

Wednesday, 6 June 2012

Jquery ajax call - jQuery.ajax()

Jquery ajax call - jQuery.ajax()

Here is the JQuery asynchronous HTTP (Ajax) request.

$(function () {
$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType

});

});


url : A string containing the URL to which the request is sent.

date: Data to be sent to the server. It is converted to a query string.

success: success(data)
A function to be called if the request succeeds.

dataType: The type of data that you're expecting back from the server.



Here is the example code in mu view file. I am uisng HAML

  :javascript
    $(function () {

    $('#party-schedule').on('show', function () {

      $.ajax({
      url: "#{party_schedules_parties_path}",
      data:'section=party',
       success:function(data){
        $('#party-schedule').html(data);
       },
      dataType:'html'
      });

    })


---------------------------------

The above ajax call will send a request to server as below:

Started GET "/parties/party_schedules?section=party" for 127.0.0.1 at 2012-06-07 11:43:19 +0530
Processing by PartiesController#party_schedules as HTML
  Parameters: {"section"=>"event"}


------------------------------------

So you need to have party_schedules method inside the parties controler to respond for this request.
When request comes to controller, it responds to respective view file.

Note: You should use render :layout => false inside the method.


Thank You,
Uma Mahesh


Sunday, 3 June 2012

active admin show page customisation

Hi,

You can customise show method in active admin for your desired output. I have customise show page to have different panels of user show page.


  show :title => "User details" do | user |
    panel "Profile Info" do
    attributes_table_for user do
      row("Name") {|user| user.p.f_name}
      row :email
      row("Company") {|user| user.p.company}
     end
    end

    panel "Email Notifications"  do
      attributes_table_for user do
        row("News Letter") { |user| user.p.notification_setting.news) }
        row("New Events") { |user| user.p.notification_setting.events) }
      end
    end
  end

Here is the link to have clear view about customisation of show page:
https://gist.github.com/986730



Thank You,
Uma Mahesh

Friday, 1 June 2012

YAML file configuration in rails application

Hi,

We may required to configure some things in rails application in configuration level. So these things can be configured in YAML file as below.


1) Create your configuration file in config/myconfig.yml

common: &default_settings
  user_settings:
    email: yes
    profile: yes
  product:
    price: yes
    image: yes

development:
  <<: *default_settings


staging:
  <<: *default_settings


production:
  <<: *default_settings


test:
  <<: *default_settings


2) It should be initialised in config/initializers/load_config.rb

APP_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/myconfig.yml")[RAILS_ENV]


3) You can access those setting any where in the application
 
   APP_CONFIG['user_settings']['email']

I came to see there is one more useful gem which can do these functionality.  Here is it YETTINGS https://github.com/charlotte-ruby/yettings


Thank You,
Uma Mahesh

couldn't parse YAML at line (Psych::SyntaxError)

I have used YML file for configuring globally few things for the application.

I have alligned the yml file with correct structure and correct indentation. Stil it trows the following error

  couldn't parse YAML at line (Psych::SyntaxError)

There is a tool YAML Lint http://www.yamllint.com/ helped me to check the yml allignment that I have coded was correct or wrong

Just copy and past your code in that site and click go It will Display the error line if you have any error's.

Thank You,
Uma Mahesh.