Wednesday, March 31, 2010

alias methods in ruby

by sandipransing 0 comments
Alias method in ruby
Ruby classes provides a alias_method that can be used to reuse the existing methods.
Consider a situation where you need different methods which has same code and ONLY they have different names.

In this case alias_method uses suits best choice instead duplicating same code or writing common method that will get used in all methods, as i did before. Example, I have methods search, home, index all are doing same functionality.
Old approach # URL / def index list end # URL /search def search list end #URL /home def home list end private def list # code here end Correct approach in ruby def index # code here end alias_method :home, :index alias_method :search, :index Attributes aliasing in ruby
Same way one can easily rename existing class attribute names using alias_attribute method.
alias_attribute(new_name, old_name) alias_attrinute :username, :login More practical use
while deprecating attributes, methods in gems, plugins, extensions, libraries always use aliases in order to maintain backward compatibility.
Got easy ??
that's where ruby rocks !
Read More…

Friday, March 26, 2010

nginx and thin installation and configuration

by sandipransing 0 comments

Install nginx server using following command

apt-get install nginx Edit nginx configuration and add server block inside html block. 
server {
    listen       80;
    server_name  boost;

    root /home/sandip/rails_app/public;

    location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

        if (-f $request_filename/index.html) {
            rewrite (.*) $1/index.html break;
        }
        if (-f $request_filename.html) {
            rewrite (.*) $1.html break;
        }
        if (!-f $request_filename) {
            proxy_pass http://thin;
            break;
        }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

Install thin server as gem
sudo gem install thin

Building native extensions.  This could take a while...
Building native extensions.  This could take a while...
Successfully installed eventmachine-0.12.10
Successfully installed thin-1.2.7
2 gems installed

Install thin service
sudo thin install
Installing thin service at /etc/init.d/thin ...
mkdir -p /etc/init.d
writing /etc/init.d/thin
chmod +x /etc/init.d/thin
mkdir -p /etc/thin

Configure thin to start at system boot
sudo /usr/sbin/update-rc.d -f thin defaults

Then put your config files in /etc/thin
sudo /usr/sbin/update-rc.d -f thin defaults
update-rc.d: warning: thin stop runlevel arguments (0 1 6) do not match LSB Default-Stop values (S 0 1 6)
 Adding system startup for /etc/init.d/thin ...
   /etc/rc0.d/K20thin -> ../init.d/thin
   /etc/rc1.d/K20thin -> ../init.d/thin
   /etc/rc6.d/K20thin -> ../init.d/thin
   /etc/rc2.d/S20thin -> ../init.d/thin
   /etc/rc3.d/S20thin -> ../init.d/thin
   /etc/rc4.d/S20thin -> ../init.d/thin
   /etc/rc5.d/S20thin -> ../init.d/thin

Create thin configuration
sudo thin config -C /etc/thin/<config-name>.yml -c <rails-app-root-path> --servers <number-of-threads> -e <environment>
</environment></number-of-threads></rails-app-root-path></config-name>

In my case,
sudo thin config -C /etc/thin/rails_app.yml -c /home/sandip/rails_app --servers 3 -e production
&gt;&gt; Wrote configuration to /etc/thin/rails_app.yml

thin configuration file will look like

Start/stop/restart Nginx &amp; thin server using command

sudo service nginx start|stop|restart
sudo service thin start|stop|restart
Read More…

Thursday, March 25, 2010

ruby on rails installation on fresh ubuntu machine

by sandipransing 0 comments

Ruby On Rails Installation on fresh ubuntu machine

Installation steps are applicable to ubuntu versions interpid, karmic koala. Make necessary changes according to package manager provided by other linux operating systems in order install ruby and rails.

Before getting started to installations make sure to build essential packages on fresh ubutnu machine. Ubuntu machine has built in apt-get package manager and that i loves because it is very to use as compared to other OS.
sudo apt-get install build-essential

Now there are many versions of ruby available including latest 1.9.2
But would like to prefer ruby version 1.8.7 as it is the most stable version as of now. I would like to recommend installtion of Ruby Enterprise Edition (REE) version as it is uses minimal system resources and consumes less memory.

Instrunctions to setup normal ruby and rails environment


1. Install Ruby, Rails, MySQL, irb and neceesary packages using single 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.1 mysql-common mysql-server-5.1 rdoc1.8 ri1.8 ruby1.8 irb libopenssl-ruby libopenssl-ruby1.8 libhtml-template-perl mysql-server-core-5.1 libmysqlclient16 libreadline5 psmisc
2. Install ruby gems
wget http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz
tar xvzf rubygems-1.3.5.tgz
cd rubygems-1.3.5
sudo ruby setup.rb
3. Create symbolic links to installation paths
sudo ln -s /usr/bin/gem1.8 /usr/local/bin/gem
sudo ln -s /usr/bin/ruby1.8 /usr/local/bin/ruby
sudo ln -s /usr/bin/rdoc1.8 /usr/local/bin/rdoc
sudo ln -s /usr/bin/ri1.8 /usr/local/bin/ri
sudo ln -s /usr/bin/irb1.8 /usr/local/bin/irb
4. Setup gemrc in order to avoid rdoc installation and to setup gem sources.
Add following lines to ~/.gemrc file
---
gem: --no-ri --no-rdoc
:benchmark: false
:verbose: true
:backtrace: false
:update_sources: true
:sources:
- http://gems.rubyforge.org
- http://gems.github.com
:bulk_threshold: 1000
5. Install rails
sudo gem install rails --no-rdoc --no-ri

Ruby Enterprise Edition i.e. REE (ruby 1.8.7) Installation


This will install ruby, rails, mysql, nginx and passenger

1. Download REE setup and install it
wget http://rubyforge.org/frs/download.php/68719/ruby-enterprise-1.8.7-2010.01.tar.gz /opt/ruby

cd /opt
./ruby/installer

2. Add ruby inside path
vi ~/.bashrc
# Add following line at the end of file
export PATH=/opt/ruby/bin:$PATH

Thanks to @vwadhwani!
Read More…

Tuesday, March 23, 2010

Download Rails API to work offline

by sandipransing 0 comments
Command to download/copy rails api to work locally(offline) mode.
wget -mk www.api.rubyonrails.org
For more information click
Read More…

Imagemagick/ RMagick Installation on ubuntu

by sandipransing 0 comments

ImageMagick Installation

Ubuntu machine has default apt-get package manager.
To install imagemagick following packages needs to be installed.

apt-get install imagemagick librmagick-ruby libmagickwand-dev

RMagick gem install

gem install rmagick

If you still facing problems with gem installation, Please look that following packages are installed
on your system.

dpkg -l | grep libmagickcore-dev graphicsmagick-libmagick-dev-compat

If there are no packages installed then try to install then first.

apt-get install libmagickcore-dev graphicsmagick-libmagick-dev-compat

Try to install rmagick gem again. Now it should be installed without any error.

Read More…

Friday, March 19, 2010

RubyConf 2009 LT "Termtter"

by sandipransing 0 comments
Check out this SlideShare Presentation:
Termtter ruby gem is provides a way to work
with twitter which is easy to use and integrate.
Basically it can be used in ruby and rails application
to get full control over twitter as like we have in web
browser. Also, it works with terminal.
Read More…

Saturday, March 13, 2010

MVC coding principles in rails

by sandipransing 0 comments
I believe this post should clear basic coding standards before getting started with rails development.
I just came with conversion started for declaring variables on rubyonrailstalk google group and that ended up with exploring the concepts of rails MVC coding principles. so, i thought it would be nice if they gets summarized somewhere.

The question raised was -
"How to declare variables like arrays so that they are available everytime that layout or its related
partials are used. Putting @myarray = MyArray.all into every action in every controller doesn't seem very dry, so I guess I'm just looking for a very simple straighforward convention, but can't seem to find it documented anywhere or figure it out" -- capsized
Before getting into actual conversion, I would like to notedown what rails is.
Rails is web framework developed in ruby language. The main purpose behind is to make programmers life easy and development would be a fun. It is  built over MVC framework and philosophy includes DRY, Convention over configuration and REST.
Pasting debate conversion as it is.
Normally something like that goes into a high-level filter, like one 
in ApplicationController.  -- Xavier Noria
 Put a before_filter in your ApplicationController.
class ApplicationController
  before_filter :set_my_array
  private
  def set_my_array
    @myarray = MyArray.all
  end
end
-- Andy

If it is literally something as simple as MyArray.all I believe there
is nothing wrong with calling the model direct from the view. -- Colin
And here goes the debate started. First of all, i was also agreed with this suggestion but next reply
started conversion.
It's dirty, horrible, bad form, breaks the separation of layers...
Don't call the model from the view! -- Andy
Beware of the MVC police Colin, this suggestion will certanly not get
good housekeeping seal of approval :D
I agree through. I'm not gonna add a before filter just to set
MyArray.all into a class variable. I'd rather call it directly and claim
to be pragmatic. --Sharagoz

But you are wrong.  The view should never, ever, ever touch the database.
Claim all you like.  The fact is that in MVC architecture, database
queries don't belong in the view.  A before_filter is the proper place
for this. --Marnen

Is it considered ok to call model methods if they do not touch the db,
or are model methods forbidden also? -- Colin
I would say the view can call instance methods of the model (attributes - real and virtual) but no class methods. So: is OK, but:
is not.  It's a bit of a contrived example, but there you go.  Accessing the model through instance variables you've created is OK, going directly to the model bypassing the controller is not. --Andy
I think it is appropriate for the view to call methods on the objects passed in by the controller, provided that these methods do not change the model or touch the database.
Example:
# controller
def my_action
 @person = Person.find(params[:id])
end
#my_action.html.erb
Good: -- Marnen

Here started conclusion on topic
Good example. I just want to throw in a couple more twists and see what
you think.
1. What about methods on models that change themselves in some way?
Suppose the last_viewed_at method returned a previously stored time,
then updated the model to store a new current time. Maybe a bad example,
but I hope you get my meaning.
2. What about aggregating class methods like count, sum or avg?
Obviously a class methods and does touch the database. I assume it would
be better to let the controller deal with stuff like this.
Controller
 @person_count = Person.count
View -- Robert
I don't know what you mean by dirty, it saves several lines of code
and when looking at the view code it is easier to see what is
happening than to see a variable that has to be hunted for in a filter
somewhere to find out what it is.
It does not break the separation of layers any more than calling an
instance method of a model does when using something like &gt; Don't call the model from the view!
@person.name is a model call from the view -- Colin
But think how many lines of code you are going to have to go edit when you realize that you need to change it. 
Also, I wouldn't consider Person.all to be more clean than @people. What if you need to exclude some? Person.all :conditions =&gt; {whatever}, if you are just using a before filter, it is easy to override, you can override it for any given controller, and for any given controller method. If it's hard coded into the view, then that view has to serve everybody's wishes, it ends up having to know how it is to be used, and having lots of brittle conditional code for each of these situations.
This is why the controller must be responsible for supplying the appropriate data to the view, not the view being responsible for creating it's own data. 
It might start as innocently as Person.all, it can easily turn into 
if this
  Person.all
elsif that
  OtherPerson.all
else
  Person.all + OtherPerson.all
end -- Josh
This took another turn in conversion -
Did you misunderstand my post?  I was arguing for putting it in a filter rather than in the view (hence saying the 4 lines of before_filter, private, def and end was worth it).
It sounds like - when you start with "But" - that you disagree, but the rest of your post seems to be arguing from the same side as my posts. -- Andy
And finally Colin ended up conversion with conclusion -
An excellent post if I may say so that brings out the salient points I
think.  Can the issues be summarised as follows?
  • The controller should provide all the data that the view should display in instance variables (@person for example).
  • The view is expected to understand the structure of the objects and so can access attributes (virtual or otherwise) of the objects.
  • If the model needs to access the db in order to provide an attribute value, or accessing the attribute has some side effect that affects the db, then this is ok, providing the view does not 'know' that the side effect or db access is happening. (Not very well written but I hope you know what I mean).
  • The view must not call any method of the model who's purpose is to perform an action rather than return a value.
  • The view should not make any explicit use of model classes.  For example there should be no reference to Person or any other model class -- Colin
Read More…

Friday, March 12, 2010

WordPress blog software installation

by sandipransing 0 comments
WordPress is a open source software developed by and for community with ongoing development on it.
Easy installation, customizable, with lots of available plugins, themes and SEO friendly are the strengths of it!
Software is mainly serves the purpose of blogging, hosting static websites.
People with knowledge of php, javascipt and little knowledge of mysql db can customize it however they want.

Minimum server requirements
  1. PHP 4.3 or greater
  2. MySQL 4.1.2 or greater
  3. apache/ngnix ( or any web server supporting php & mysql )

For detailed information on installation click

Now you will need to decide where on your web site you'd like your blog to appear:
In the root directory of your web site. (For example, http://yoursite.com/)
In a subdirectory of your web site. (For example, http://yoursite.com/blog/
This can be done by adding new route at nginx configuration file or deploying wordpress
software inside blog directory of main website.

There are millions of satisfied users using word-press blog.
To create and start blogging with free wordpress.com blog click


WordPress MU multiblog software provides a way to create thousands of wordpress blogs
just like wordpress.com site does.

Download and detailed information on installation click

Read More…

require file in rails environment

by sandipransing 0 comments

There are different ways to load particular file in rails application environment if the required file exists.
1. Using RAILS_ROOT
if File.exists?(file=File.join(RAILS_ROOT,'config', 'initializers', 'smtp_gmail.rb'))
  require file
end
2. Using Rails.root &amp; join
require Rails.root.join('config', 'initializers', 'smtp_gmail.rb')
3. Using Rails.root, join &amp; exists? method.
require file if File.exists?(file = Rails.root.join('config', 'initializers','smtp_gmail.rb'))
4. Using File and direct path to file
require  File.join('root','app','config', 'initializers', 'smtp_gmail.rb')
Among all above methods of  loading file, Using Rails.root, join &amp; exists? method seems to be pretty good to have.
Any improvements are most welcome!
Read More…

Thursday, March 11, 2010

alternative for tortoise svn on ubuntu

by sandipransing 0 comments
The Tortoise svn client on windows is one of my favorite svn client.
I am working on ubuntu karmic koala from last one year.
There are kdesvn. smartsvn svn clients available on ubuntu but still
time haven't found any svn client as good as tortoise svn on windows.

Is there any alternative ??? Can tortoise svn client installation possible
using wine utility package in ubuntu ??

Read More…

blogger tips

by sandipransing 0 comments
Change default favicon on blogger
Go to the layout click on Edit HTML link
Insert following link code inside head tag
<link href='IMAGE_ICON_LINK' rel='icon' type='image/x-icon'/>
Replace IMAGE_ICON_LINK url with your icon file url on web


Use Dynamic DriveFavIcon Generator online tool to easily create a favorites icon (favicon) for your site



Read More…

Saturday, March 6, 2010

Rails Tiny MCE - A Rich Text Editor for ruby on rails

by sandipransing 0 comments

RailsTinyMCE - A Rich Text Editor for ruby on rails

TinyMCE is a javascript rich text editor. It is easy to integrate with blogs, cms, messages and mailers.
Plugin uses jrails(jquery) and paperclip plugin for upload support.

Features

  • Provides rich text editor
  • Customisable TinyMCE plugins
  • Easy to integrate
  • Supports Image upload & insert
  • Supports Media upload & Youtube embed
  • TODO: Document upload plugin

1. Install rails_tiny_mce plugin using

./script/plugin install git://github.com/sandipransing/rails_tiny_mce.git
./script/generate rails_tiny_mce_migration
rake db:migrate

2. Install jrails(jquery) plugin using

./script/plugin install git://github.com/aaronchi/jrails.git

3. Install dependent plugins(if you didn't)

rake rails_tiny_mce:plugins
Above command will copy paperclip, responds_to_parent, will_paginate plugins to vendor/plugins directory.
  • paperclip git://github.com/thoughtbot/paperclip.git
  • responds_to_parent http://responds-to-parent.googlecode.com/svn/trunk
  • will_paginate git://github.com/mislav/will_paginate.git

4. In your layout add following lines

<%= javascript_include_tag :defaults %>
<%= javascript_include_tiny_mce_if_used %>
<%= tiny_mce if using_tiny_mce? %>

5. Inside controller class on top add following lines

uses_tiny_mce(:options => AppConfig.default_mce_options, :only => [:new, :edit])
This AppConfig.default_mce_options is in config/initializers/tiny_mce_plus_config.rb, you could change the setting there

6. In your view add class mceEditor to text_area

Then append the following to the text area you want to transform into a TinyMCE editor.
:class => "mceEditor"

7. Install file lists

rake rails_tiny_mce:install
will Install following files:
app
  |-- controller
    |-- attachments_controller.rb
  |-- helpers
    |-- remote_link_renderer.rb
  |-- models
    |-- print.rb
    |-- video.rb
  |-- views
    |-- attachments
       |-- _show_attachment_list.html.erb
config
  |-- initializers
    |-- tiny_mce_plus_config.rb
public
  |-- images
    |-- tiny_mce
  |-- javascripts
    |-- tiny_mce
You may custom the config in tiny_mce_plus_config.rb.

Attention Note:

  • Do not put <p> </p> around the textarea.
  • If you are using old will_paginate plugin, change the url_for to url_option in remote_link_renderer.rb

Example use:


  • Create CRUD for post
    ./script/generate scaffold post title:string text:description

  • Run Migrations
    rake db:migrate

  • Add following line to posts_controller.rb
    uses_tiny_mce(:options => AppConfig.default_mce_options, :only => [:new, :edit])

  • Open /views/posts/new.html.erb and /views/posts/edit.html.erb

  • Modifiy following line
    <%= f.text_area :description %> to <%= f.text_area :description, :class => "mceEditor" %>
Read More…

Thursday, March 4, 2010

Page Cache control in radiant cms

by sandipransing 0 comments
Radiant Caching

Radiant cms is very powerful and customizable cms as of now which has inbuilt support for page caching.
Radiant caching mechanisam is somehow similar to action caching in rails.

In latest radiant version i.e. > 0.8 Responsecache has been replaced with Radiant::Cache.

By default radiant cache gets automatically invalidated after every 5 
minutes and that is configurable.

The interval is easily configurable by adding following lines inside environment

if defined? ResponseCache == 'constant'    
    ResponseCache.defaults[:expire_time] = 4.hours
else
    SiteController.cache_timeout = 4.hours
end
There are situations where automatic cache inavalidation won't work
and we need to clear radiant cache on the fly.
There are two ways to do that to invalidate radiant cache immediately.

1. Navigate to the root of your Radiant project and delete the cache directory.

cd /home/deploy/radiant_site/tmp
rm -r cache

2. Clearing the page cache from within your code
    
if defined? ResponseCache == 'constant'
    ResponseCache.instance.clear
else
    Radiant::Cache.clear
end

While building website using radiant cms, it happens that there are certain pages they are static and not going to change frequently that time configuring cache expiry time to long interval is going to be always beneficial and for pages which conatins dynamic content (displaying logged in user on homepage), we need to disable radiant cache for such pages. this can be done by using page_options extension.

Installation for radiant version  0.7
From your RADIANT_ROOT:

$ script/extension install page_options

Installation for radiant version  0.8 and higher
git clone git://github.com/sandipransing/radiant-page_options-extension.git vendor/extensions/page_options

Restart server

Usage

1. Goto /admin/pages
2. Edit any page
3. Click on more link and edit cache settings.

For more information visit

Read More…

Tuesday, March 2, 2010

Programming ruby Linux basics

by sandipransing 0 comments
Remove svn files inside directory
rm -rf `find . -type d -name .svn


Set path in linux
export PATH=$PATH:/usr/ruby/bin
Here /usr/ruby/bin is the path to ruby extecuatble.

grep and print process pid
ps -ef | grep search_string | grep -v grep | awk '{print  $2 }'


Kill process
kill -9 process_id_here
ps -ef | grep search_string | grep -v grep | awk '{print  $2 }' | xargs kill -9


Store pid of process in a variable for further process
tokill=`ps -ef|grep ruby|grep -v grep|awk '{print $2}'`;kill -9 $tokill;


Mirror a website
Command to clone/copy a website for offline/local browsing.
wget -mk www.funonrails.com

Above command downloads all website pages in depth level with stylesheets, images and javascripts.
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