Friday, May 22, 2009

Intresting String inflections in rails

by sandipransing 1 comments
* camelcase
* camelize
* classify
* constantize
* dasherize
* demodulize
* foreign_key
* humanize
* parameterize
* pluralize
* singularize
* tableize
* titlecase
* titleize
* underscore


camelcase(first_letter = :upper)

Alias for camelize
camelize(first_letter = :upper)

By default, camelize converts strings to UpperCamelCase. If the argument to camelize is set to :lower then camelize produces lowerCamelCase.

camelize will also convert ’/’ to ’::’ which is useful for converting paths to namespaces.

"active_record".camelize # => "ActiveRecord"
"active_record".camelize(:lower) # => "activeRecord"
"active_record/errors".camelize # => "ActiveRecord::Errors"
"active_record/errors".camelize(:lower) # => "activeRecord::Errors"

This method is also aliased as camelcase

classify()

Create a class name from a plural table name like Rails does for table names to models. Note that this returns a string and not a class. (To convert to an actual class follow classify with constantize.)

"egg_and_hams".classify # => "EggAndHam"
"posts".classify # => "Post"

Singular names are not handled correctly.

"business".classify # => "Busines"

constantize()

constantize tries to find a declared constant with the name specified in the string. It raises a NameError when the name is not in CamelCase or is not initialized.

Examples

"Module".constantize # => Module
"Class".constantize # => Class

dasherize()

Replaces underscores with dashes in the string.

"puni_puni" # => "puni-puni"

demodulize()

Removes the module part from the constant expression in the string.

"ActiveRecord::CoreExtensions::String::Inflections".demodulize # => "Inflections"
"Inflections".demodulize # => "Inflections"


foreign_key(separate_class_name_and_id_with_underscore = true)

Creates a foreign key name from a class name. separate_class_name_and_id_with_underscore sets whether the method should put ‘_’ between the name and ‘id’.

Examples

"Message".foreign_key # => "message_id"
"Message".foreign_key(false) # => "messageid"
"Admin::Post".foreign_key # => "post_id"

humanize()

Capitalizes the first word, turns underscores into spaces, and strips ‘_id’. Like titleize, this is meant for creating pretty output.

"employee_salary" # => "Employee salary"
"author_id" # => "Author"

parameterize()

Replaces special characters in a string so that it may be used as part of a ‘pretty’ URL.
Examples

class Person
def to_param
"#{id}-#{name.parameterize}"
end
end

@person = Person.find(1)
# => #


# => Donald E. Knuth

pluralize()

Returns the plural form of the word in the string.

"post".pluralize # => "posts"
"octopus".pluralize # => "octopi"
"sheep".pluralize # => "sheep"
"words".pluralize # => "words"
"the blue mailman".pluralize # => "the blue mailmen"
"CamelOctopus".pluralize # => "CamelOctopi"

singularize()

The reverse of pluralize, returns the singular form of a word in a string.

"posts".singularize # => "post"
"octopi".singularize # => "octopus"
"sheep".singularize # => "sheep"
"word".singularize # => "word"
"the blue mailmen".singularize # => "the blue mailman"
"CamelOctopi".singularize # => "CamelOctopus"

tableize()

Creates the name of a table like Rails does for models to table names. This method uses the pluralize method on the last word in the string.

"RawScaledScorer".tableize # => "raw_scaled_scorers"
"egg_and_ham".tableize # => "egg_and_hams"
"fancyCategory".tableize # => "fancy_categories"

titlecase()

Alias for titleize
titleize()

Capitalizes all the words and replaces some characters in the string to create a nicer looking title. titleize is meant for creating pretty output. It is not used in the Rails internals.

titleize is also aliased as titlecase.

"man from the boondocks".titleize # => "Man From The Boondocks"
"x-men: the last stand".titleize # => "X Men: The Last Stand"

This method is also aliased as titlecase

underscore()

The reverse of camelize. Makes an underscored, lowercase form from the expression in the string.

underscore will also change ’::’ to ’/’ to convert namespaces to paths.

"ActiveRecord".underscore # => "active_record"
"ActiveRecord::Errors".underscore # => active_record/errors
Read More…

Render partial or view from another controller

by sandipransing 0 comments
To render view from another controller

# In rail 2.3
render "controller/action"

# In rails 2.2 or below
render :template => 'controller/action'

To render partial from another controller's views folder

render :partial => "controller/partial"

Cheers !
Sandip
Read More…

vi / vim Shortcuts

by sandipransing 2 comments
Open file
vi filename
As i am newb on linux macine, i dont know vi shortcuts.
so, i am listing down shortcuts which i am getting familier. :)

Insert in file
i

Exit file
q

forced exit
q!

save file
wq

forced save
wq!

Copy no of lines
yy

Paste copied lines
pp

Undo changes
uu

Delete lines
dd

To search and replace string in vi
:%s/search_string/replacement_string/g

To find particular word in file
?string1

If you have any quick list. please, let me know
Read More…

Wednesday, May 13, 2009

Working with multiple ruby versions on same server

by sandipransing 1 comments
click for original postNice post by Michael Greenly

I recently changed how I'm handling multiple simultaneous Ruby installations and I'd like to share.

What I needed was to make it convenient to switch between the system provided packages and specific, from source, installations. After some experiments I decided to use 'update-alternatives' to do it.

Here's a quick walk through...

First I removed all of my Ruby and RubyGem environment variables, they're not needed.

Then I installed Ubuntu's default Ruby packages via apt-get.

$ sudo apt-get install ruby irb ri rdoc libruby-extras rubygems ruby1.8-dev


Next I downloaded and installed alternate versions of Ruby from source. In this example I'm going to use two additional versions; the newest stable release and the newest development release.

$ cd /tmp
$ wget -c ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p71.tar.gz
$ tar -xvzf ruby-1.8.7-p71.tar.gz
$ cd ruby-1.8.7-p71
$ ./configure --prefix=/opt/ruby-1.8.7-p71
$ make
$ sudo make install
$ wget -c ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.0-3.tar.gz
$ tar -xvzf ruby-1.9.0-3.tar.gz
$ ./configure --prefix=/opt/ruby-ruby-1.9.0-3
$ make
$ sudo make install


At this point I have three versions of Ruby installed and each can be accessed through it's full path.

$ /usr/bin/ruby --version
# ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]
$ /opt/ruby-1.8.7-p71/bin/ruby --version
# ruby 1.8.7 (2008-08-08 patchlevel 71) [i686-linux]
$ /opt/ruby-1.9.0-r18217/bin/ruby --version
# ruby 1.9.0 (2008-07-25 revision 18217) [i686-linux]


You'll also notice that the default installation is the one provided by Ubuntu.

$ ruby --version
# ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]


Next we'll use 'update-alternatives' to make it a bit easier to switch between them. You could do this on the command line but it becomes a fairly long nasty command so I found it easier to write a quick shell script and run it. The script:

update-alternatives --install \
/usr/local/bin/ruby ruby /usr/bin/ruby 100 \
--slave /usr/local/bin/erb erb /usr/bin/erb \
--slave /usr/local/bin/gem gem /usr/bin/gem \
--slave /usr/local/bin/irb irb /usr/bin/irb \
--slave /usr/local/bin/rdoc rdoc /usr/bin/rdoc \
--slave /usr/local/bin/ri ri /usr/bin/ri \
--slave /usr/local/bin/testrb testrb /usr/bin/testrb

update-alternatives --install \
/usr/local/bin/ruby ruby /opt/ruby-1.8.7-p71/bin/ruby 50 \
--slave /usr/local/bin/erb erb /opt/ruby-1.8.7-p71/bin/erb \
--slave /usr/local/bin/gem gem /opt/ruby-1.8.7-p71/bin/gem \
--slave /usr/local/bin/irb irb /opt/ruby-1.8.7-p71/bin/irb \
--slave /usr/local/bin/rdoc rdoc /opt/ruby-1.8.7-p71/bin/rdoc \
--slave /usr/local/bin/ri ri /opt/ruby-1.8.7-p71/bin/ri \
--slave /usr/local/bin/testrb testrb /opt/ruby-1.8.7-p71/bin/testrb

update-alternatives --install \
/usr/local/bin/ruby ruby /opt/ruby-1.9.0-r18217/bin/ruby 25 \
--slave /usr/local/bin/erb erb /opt/ruby-1.9.0-r18217/bin/erb \
--slave /usr/local/bin/gem gem /opt/ruby-1.9.0-r18217/bin/gem \
--slave /usr/local/bin/irb irb /opt/ruby-1.9.0-r18217//bin/irb \
--slave /usr/local/bin/rdoc rdoc /opt/ruby-1.9.0-r18217/bin/rdoc \
--slave /usr/local/bin/ri ri /opt/ruby-1.9.0-r18217/bin/ri \
--slave /usr/local/bin/testrb testrb /opt/ruby-1.9.0-r18217/bin/testrb


What that does is create a group of applications under the generic name Ruby. In addition each application has several slave applications tied to it; erb, irb, etc... In defining each application we specify what symbolic link it will be accessed through and where the application is actually installed. In my case Ubuntu installed Ruby in /usr/bin and the source installed versions are in /opt. All of the installations will be accessed through the generic name Ruby and will have there symbolic links created in /usr/local/bin. I choose /usr/local/bin because it supercedes /usr/bin in the default path.

Before moving on make sure that 'update-alternatives' sees all of our Ruby installations:

$ update-alternatives --list ruby
# /opt/ruby-1.9.0-r18217/bin/ruby
# /opt/ruby-1.8.7-p71/bin/ruby
# /usr/bin/ruby


Now switching between them is as easy as running the 'update-alternatives' command and selecting the number of the installation you'd like to use. Example:

$ sudo update-alternatives --config ruby


It's important to keep in mind that each installation is separate. So for example if you install RubyGems while using /usr/bin/ruby it will not be available to /opt/ruby-1.9.0-r18217/bin/ruby, or /opt/ruby-1.8.7-p71/bin/ruby, etc....

While it's probably possible to use a shared repository for RubyGems across multiple installations I haven't tried it and instead have choosen to use multiple separate RubyGem installs, one for each Ruby installation.

Also RubyGem's bindir will most likely not be in your path. To get around this I created a short script called 'gemexec' in /usr/local/bin

#!/usr/bin/env ruby

require 'rubygems'

if ARGV.size > 1
exec "#{Gem.bindir}/#{ARGV.shift}",ARGV.join(" ")
else
exec "#{Gem.bindir}/#{ARGV.shift}"
end


This script uses the RubyGems installation of the currently selected Ruby to determine where the executable gem should be found, then runs it with any additional command line arguments provided. example:

$ gemexec rake --version
# rake, version 0.8.1


With all that in place the only thing to watch out for is other peoples scripts that hardcode the shebang line with something like "#!/usr/bin/ruby". What I do myself, and prefer in general, is to use "#!/usr/bin/env ruby".
Read More…

Ruby 1.8.7 and rails installation on ubuntu interpid

by sandipransing 1 comments
Execute following commands in order to install ruby and rails.

sudo apt-get install build-essential

Below command will install all necessary packages.
if you dont want any remove it from command.

sudo apt-get install ruby ri rdoc mysql-server libmysql-ruby ruby1.8-dev irb1.8 libdbd-mysql-perl libdbi-perl libmysql-ruby1.8 libmysqlclient15off libnet-daemon-perl libplrpc-perl libreadline-ruby1.8 libruby1.8 mysql-client-5.0 mysql-common mysql-server-5.0 rdoc1.8 ri1.8 ruby1.8 irb libopenssl-ruby libopenssl-ruby1.8 libterm-readkey-perl psmisc

Gem Installation
Please find latest stable gem version on rubyforge.

wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz
tar xvzf rubygems-1.3.1.tgz
cd rubygems-1.3.1
sudo ruby setup.rb


And last to install rails without documentation

sudo gem install rails --no-rdoc --no-ri

and finally rails server, you can install apache mongrel, nginx + thin, whichever you feel suitable.

for mongrel install

sudu gem install mongrel
Read More…

Fix for ruby 1.8.7 incompatibity

by sandipransing 0 comments
Last week i moved from ruby version 1.8.6 to 1.8.7.
then over a week i found that my 1.2.3 and applications developed in ruby 1.8.6 are not working in ruby 1.8.7.

From lot of search on google, i found that its issue with ruby 1.8.7.

Then, i started searching fix / solution for this incompatibity.
And, Finally i got solution.

We just need to fix file delegate.rb
here is fix

Diff of /branches/ruby_1_8_7/lib/delegate.rb

--- branches/ruby_1_8_7/lib/delegate.rb 2008/05/31 15:17:53 16732
+++ branches/ruby_1_8_7/lib/delegate.rb 2008/06/02 10:52:07 16756
@@ -163,9 +163,9 @@
# Checks for a method provided by this the delegate object by fowarding the

# call through \_\_getobj\_\_.
#
- def respond_to?(m)
+ def respond_to?(m, include_private = false)
return true if super
- return self.__getobj__.respond_to?(m)
+ return self.__getobj__.respond_to?(m, include_private)

end

#
@@ -270,9 +270,9 @@
end
@_dc_obj.__send__(m, *args)
end
- def respond_to?(m) # :nodoc:
+ def respond_to?(m, include_private = false) # :nodoc:
return true if super

- return @_dc_obj.respond_to?(m)
+ return @_dc_obj.respond_to?(m, include_private)
end
def __getobj__ # :nodoc:
@_dc_obj

You have to make necessary changes and you are ready to work with ruby 1.8.7.
need not downgrade ruby version :)

for Hash error

Add following line in config/environment.rb
unless '1.9'.respond_to?(:force_encoding)
String.class_eval do
begin
remove_method :chars
rescue NameError
# OK
end
end
end


Cheers !

Sandip
Read More…

Rails Coding Standards

by sandipransing 1 comments
IN ESSENCE: ALL CODE SHOULD BE READABLE!

# DO NOT OPTIMISE for performance - OPTIMISE FOR CLARITY OF CODE

# STYLE: use 2 spaces for indent (not tabs)

# STYLE: Line up hash arrows for readability

# STYLE: put spaces around => hash arrows

# STYLE: put spaces after ',' in method params - but none between method names and '('

# VIEWS: use HAML for views

# VIEWS: break up the structure with white space to help readability - VERTICALLY TOO!

# VIEWS STYLE: Rely on structure of page, without having to insert messages or new components...

# LOGIC: Rails Models should be as heavy as in logic and controllers should be lightweight as much as .

* Example: Effect to visually highlight then drop out an existing element rather than flash a message

* Example: Highlight newly added row rather than a message about it

# AVOID logic in views - they should be simple

# Views indentation should be well formatted.
not like this

<% for joke in @jokes %>
<div class="joke">
<p>
<%= h(truncate(joke.joketext, 20)) %>
<%= link_to 'Read this joke', {:action => 'show_joke', :id => joke} %>
</p>
<p class="author>
by <%= h(joke.author.full_name) %></p>
</div>
<% end %>


* put html generating logic into helpers

* instead of inline ruby logic, add to models (filtering, checking)

# NEVER use ActiveRecord models in migrations unless you re-define them within the migration

* ...otherwise the migration fails when you later remove/rename the AR class

* BETTER SOLUTION: use bootstrapping until deployed!!!

# AJAX only for sub-components of an object, and avoid over-use




CONTROLLER CODING STANDARDS


1. Before filter should be added at the top of controller.

2. Before filter implementation should be immediate after filter declaration

3. Standard rails actions

4. Own custom actions

5. Inter-related actions should be clubbed together.

6. please, try to use of protected, private methods and they should be declared at the bottom of page in order.

7. Controller Actions should be like -
use 2 spaces for indent (not tabs)

def self.published_jokes
find(:all, :conditions => "published = 1")
end


MODEL CODING STANDARDS


#======= HEADER SECTION=========


# SCHEMA INFORMATION WILL BE HERE
# REQUIRE FILES WILL GO HERE


class Model < ActiveRecord::Base

#======== TOP ===================

# LIBRARY OR INCLUDE METHODS
# MODEL RELATIONSHIPS
# VIRTUAL ATTRIBUTES
# ACTIVE RECORD VALIDATIONS

#======== MIDDLE ===============
# CUSTOM VALIDATIONS
# PUBLIC METHODS

#======== BASE ==================
# PROTECTED METHODS
# PRIVATE METHODS

end

Cheers !!!
Sandip
Read More…

Friday, May 8, 2009

High Performance Rails Hosting

by sandipransing 1 comments
There are lot of rails hosting, like wired tree,...,
i am still in search of cost effective and high performance hosting.

recently i came across with joyent rails hosting, please let me know your opinions..


Scale on Demand

Your rails infrastructure can be dynamically expanded or reduced within minutes.

Support Billions of Hits

The largest ruby on rails application running on Joyent does over 1 Billion page views a month. Joyent's hardware load balancers make this kind of scale possible.
Ruby 1.8.6, Rails 2.1, Mongrel, Nginx

Everything you need to get rolling is pre-installed, including Ruby 1.8.6 and Rails 2.1, Apache, lighttpd, nginx and Mongrel.

Extremely Cost Effective

Static IPs, real storage, 10TB data transfer / bandwidth, and fantastic support all included.
Lightning Fast Speed

We provide direct connections to tier 1 internet back-bones, Force10 switches and f5 BigIP load-balancers.

Trusted by Companies like LinkedIn


Check out their post
Official Ruby on Rails Host

We're the Official Ruby on Rails host. Go check it out at rubyonrails.org. "If you need hosting, Joyent is the official Ruby on Rails host, offering fantastic plans with a knowledgeable staff. Whether you need shared or dedicated hosting, these guys are experts in Ruby on Rails. "
Leverage a Large Community

Over 2,400 companies run Rails applications on Joyent. You gain from our experience hosting them and you can connect directly with them through the Joyent Forums and the Joyent Wiki

Entirely Open Loving Cloud

Joyent offers open protocols, open source solutions. Use any Language, any DB. You can move your application. No vendor lock-in.

please, help me......:(
Read More…

Awesome: Working with the Rails console and all the tricks

by sandipransing 1 comments
Testing your active record methods using script/console

If you are using windows, you start the console by using this command:

ruby script\console
Linux:

./script/console

Just use the following command whenever you make changes to your model objects:

reload!

Instead of accessing your MySQL database with

mysql -u -p

You can instead do

script/dbconsole

and if you database has a password, just do

script/dbconsole -p


% script/dbconsole # connect to development database (or $RAILS_ENV)
% script/dbconsole production # connect to production database


Cheers !

$@ndip
Read More…

using rails acts as taggable on plugin

by sandipransing 1 comments
A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.

Plugin Installation

script/plugin install git://github.com/mbleigh/acts-as-taggable-on.git

Gem Installation


gem install mbleigh-acts-as-taggable-on --source http://gems.github.com


Auto Install
include following line in environment.rb

config.gem "mbleigh-acts-as-taggable-on", :source => "http://gems.github.com", :lib => "acts-as-taggable-on"


Post Installation (Rails)

1. script/generate acts_as_taggable_on_migration
2. rake db:migrate


Usage
Add following line in your model for which you wanted to be tagged.

acts_as_taggable_on :tags

Example

class Post < ActiveRecord::Base
acts_as_taggable_on :tags
end


In your View for Post




In your controller create action

@post = Post.new (params[:post])
# Or just hardcode to test
@post.tag_list ="awesome, slick, hefty"
@post.save


What are the methods provided ??

@post.tag_list = "awesome, slick, hefty"

Post.tagged_with("awesome", :on => :tags) # => [@post1, @post2]


Post.tag_counts # => [,...]

Named Scope

class Post "created_at DESC"
end


Post.tagged_with("awesome").by_creation

Pagination can be added on list of tags using will_paginate plugin

List Of Tags .paginate(:page => params[:page], :per_page => 20)


@post.find_related_tags # => will give related posts having related tags. [ @post1, @post2, ...]



Tag Owners

class User < ActiveRecord::Base
acts_as_tagger
end



class Post < ActiveRecord::Base
acts_as_taggable_on :tags
end


@some_user.tag(@some_post, :with => "paris, normandy", :on => :tags)
@some_user.owned_taggings
@some_user.owned_tags
@some_post.tags_from(@some_user)



Cheers !
$@ndip
Read More…

About The Author

Sandip is a ruby on rails developer based in pune and also a blogger at funonrails. Opensource contributor and working with Josh software Private Limited. for more info read Follow Sandip on Twitter for updates.

Connect With Me...

Github Projects

@sandipransing Twitter