Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts

Wednesday, August 11, 2010

Ruby on Rails: Route: Change routing / url link

1. Show "mydomain.com/products" instead of "mydomain.com/catalogs/list"

Add this line to /config/routes.rb

map.connect 'products', :controller => 'catalogs', :action => 'list'


2. Retrieve url parameter: www.domain.com/products/34/d24s34/book

Add this line to /config/routes.rb

map.connect 'products/:id/:ref/:type', :controller => 'catalogs', :action => 'list'


catalogs_controller.rb

@id = params[:id]
@reference = params[:ref]
@type = params[:type]


Tuesday, July 27, 2010

Ruby on Rails : Ajax : link_to/form_for onclick loading effect

Link with Ajax loading image in view.rhtml:


<div id="showlist">

<%= link_to_remote "Search",
:url => { :action => "create" },
:update => "showlist",
:loading => "document.getElementById('spinner').style.visibility='visible';" %>

<img src="http://www.insight24.com/view/insight24/img/loading.gif" style="visibility:hidden;" id="spinner">

</div>



Form with Ajax loading image in view.rhtml:


<% remote_form_for :search, @search,
:url => {:action => 'create'},
:loading => "document.getElementById('spinner').style.visibility='visible';",
:update => "showlist" do |f| %>

Keyword: <%= text_field 'search', 'item' %><%= submit_tag "Search"%>
<img src="loading.gif" style="visibility:hidden;" id="spinner">
<% end %>

<div id="showlist"></div>


See also: Simple Ajax Search Engine

Saturday, July 3, 2010

Ruby on Rails: Array : Nil item

@array = [ 1, nil, 3, nil, 5 ]

Remove nil item

@array.compact    #=> [ 1, 3, 5 ]


Count total of nil item

@array.length    #=> 5
@array.nitems    #=> 3
total_nil = @array.length - @array.nitems


Check the present of nil item

@array.include?nil    #=> true


Location of the nil item

@array.index(nil)    #=> 1



Refer site: http://ruby-doc.org/core/classes/Array.html


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Wednesday, June 23, 2010

Ruby on Rails: Use cron job to do automatic refresh

Offline rebuild the Xapian Indexes
1. Goto directory
2. To get into the cron and set your schedule

crontab -e



* * * * * cd /var/www/rails_app && /usr/bin/rake xapian:rebuild_index models="Post"

(Note: rebuild index every minute)

Automatic refresh Ruby file
1. Goto directory
2. To get into the cron and set your schedule

crontab -e


* * * * * /usr/bin/ruby /var/www/rails_app/script/runner /var/www/rails_app/
app/dotask.rb

or

* * * * * /usr/bin/ruby /var/www/rails_app/app/dotask.rb

(Note: Make sure is the correct directory)

Related Link:
http://seanbehan.com/
http://www.hostingrails.com/

Ruby on Rails: Request Url

<%= request.request_uri %> / <%= request.path%>
- display current url without base url
eg: /goldberg/auth/login

<%= request.referer %>
- display previous url with base url
eg: http://www.yoursite.com/goldberg/auth/login

<%= request.env['HTTP_HOST']%>
- display base url
eg: www.yoursite.com

<%= request.env['SERVER_PROTOCOL']%>
- display protocol
eg: HTTP/1.1

<%= request.url%>
- full url
eg: http://www.yoursite.com/goldberg/auth/login

<%= request.query_parameters.size %>
- display how many parameters found in current url
url eg: www.yoursite.com/index.html?key=3&d=4
answer: 2 => (2 parameters)

<%= request.path_parameters['controller'] %>
- display controller name from current url
eg: goldberg/auth

<%= request.path_parameters['action'] %>
- display action name from current url
eg: login

<%= request.inspect%>
- It will tell you everything thats inside request.(Long request)



If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Ruby on Rails: Crontab (Cron Job) Reference

1. Commands

crontab -e
- Edit your crontab file, or create one if it doesn’t already exist.
crontab -l
- Display your crontab file.
crontab -r
- Remove your crontab file.
crontab -v
- Display the last time you edited your crontab file. (This option is only available on a few systems.)

2. Syntax
A crontab file has five fields for specifying day , date and time followed by the command to be run at that interval.
* * * * *  [ command statement to be executed ]
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
* in the value field above means all legal values as in braces for that column.
The value column can have a * or a list of elements separated by commas. An element is either a number in the ranges shown above or two numbers in the range separated by a hyphen (meaning an inclusive range).

3. Example
A line in crontab file like below removes the tmp files from /home/someuser/tmp each day at 6:30 PM.

30 18 * * * rm /home/someuser/tmp/*

Changing the parameter values as below will cause this command to run at different time schedule below :
MinHourDay/monthMonthDay/weekExecution Time
30011,6,12*– 00:30 Hrs on 1st of Jan, June & Dec.
020*101-5–8.00 PM every weekday (Mon-Fri) only in Oct.
001,10,15**– midnight on 1st ,10th & 15th of month
5,10010*1– At 12.05,12.10 every Monday & on 10th of every month

Note : If you inadvertently enter the crontab command with no argument(s), do not attempt to get out with Control-d. This removes all entries in your crontab file. Instead, exit with Control-c.

4. Crontab Environment
cron invokes the command from the user’s HOME directory with the shell, (/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user’s-home-directory
LOGNAME=user’s-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh

Users who desire to have their .profile executed must explicitly do so in the crontab entry or in a script called by the entry.

5. Disable Email
By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line .

>/dev/null 2>&1

6. Generate log file
To collect the cron execution execution log in a file :

30 18 * * * rm /home/someuser/tmp/* > /home/someuser/cronlogs/clean_tmp_dir.log


Related Link:
http://adminschoice.com/

Monday, June 21, 2010

PHP: Compare Simple UTC timestamp with Ruby on Rails

In PHP

<?
echo gmdate("Y-m-d\TH:i:s\Z", time()); //2010-06-22T03:13:05Z

echo strtotime(gmdate("Y-m-d\TH:i:s\Z", time())); //1277176425
?>


In Ruby on Rails

<%= Time.now.utc %> # Tue Jun 22 03:13:05 UTC 2010

<%= Time.now.utc.to_i %> # 1277176425




If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Wednesday, June 16, 2010

Ruby on Rails: How to uninstall a plugin in Rails

To uninstall a plugin, you can:

Case A:
1. Before you uninstall the plugin, you have to get its name. Go to the vendors directory in your app folder and get the name of the folder



2. In this case the name of the plugin is “active_scaffold”

3. Go to the directory of the app you want the plugin removed from and type in
ruby script/plugin remove active_scaffold

4. or if you’re on a Linux box
./script/plugin remove active scaffold

Case B:
- Delete the specific folder for the plugin

Case C:
- Remove it with svn delete

Case D:
- Unlink it with svn propdel svn:externals vendor/plugins/

Case E:

Ruby on Rails: Acts_as_xapian: Search engine (plugin)

Installing Xapian

The first step to installing Xapian is to download the latest version of xapian-core and extract:

curl -O http://oligarchy.co.uk/xapian/1.0.10/xapian-core-1.0.10.tar.gz
tar -xzvf xapian-core-1.0.10.tar.gz

From here, we need to configure and build the Xapian library:

cd xapian-core-1.0.10
./configure
make
sudo make install

Once this is complete, we need to download the Xapian bindings, which will let Xapian interact with Ruby, PHP and other scripting languages:

curl -O http://oligarchy.co.uk/xapian/1.0.10/xapian-bindings-1.0.10.tar.gz
tar -xzvf xapian-bindings-1.0.10.tar.gz

Again, now that we have downloaded them, we need to configure and build the Xapian-bindings:

cd xapian-bindings-1.0.10
./configure
make
sudo make install

Once that finishes, Xapian will be installed on your system. Of course, these instructions are for installing from source. If you are using a system that has aptitude installed, or another package manager, you can also install Xapian that way. For example, to install Xapian using aptitude:

aptitude search xapian

You need the following two files to complete the install:

libxapian15 - search engine library
libxapian-ruby1.8 - xapian search engine inferface for Ruby 1.8


Finally, simply enter the following commands to install the necessary components:

sudo aptitude install libxapian15
sudo aptitude install libxapian-ruby1.8

or

sudo apt-get install libxapian15 libxapian-ruby1.8

For more detailed instructions, visit http://xapian.org/docs/install.html.

Installing the acts_as_xapian Rails plugin

script/plugin install git://github.com/frabcus/acts_as_xapian.git vendor/plugins/acts_as_xapian

Once the plugin is installed, run the migrations to add the required tables to your database:

script/generate acts_as_xapian
rake db:migrate


Setting Up The Models Code

To include fields to your index, you will need to add an “acts_as_xapian” call to the model you want to index.

class Lesson < ActiveRecord::Base
acts_as_xapian :texts => [:name, :description]
end

In this case, only the data found in the “name” and “description” attributes of our Lesson model will be searched.

Building and Updating the Xapian Indexes

Xapian indexing takes place “offline,” which means that the index is not automatically updated after a model/database is changed. While this may change in the future, currently the index must be built and updated periodically by you, or using a cron job (See Crontab Reference).

At this point, you can quickly test that your Xapian install, plugin, and model code are all working together via the following rake commands:

To build the index:
rake xapian:rebuild_index models="Post"

** do cron job for rebuild_index for automatically updated after a model/database is changed
** if you have more than 1 model to build the index, rake xapian:rebuild_index models="ModelName1 ModelName2"
eg: rake xapian:rebuild_index models="Post Lesson"

To update index:
rake xapian:update_index

To test index:
rake xapian:query models="Post" query="golf"


In controller.rb

query = 'software'

Basic Search:
search = ActsAsXapian::Search.new([Post], query, :limit => 15)
@posts = search.results.collect {|p| p[:model]}

Similar Results:
similar = ActsAsXapian::Similar.new([Post], @posts, :limit => 15)
@similar_posts = similar.results.collect {|p| p[:model]}


In views.html.erb

<% for post in @posts %>
<%= post.name%><br>
<% end %>



Related Link:
http://github.com/frabcus/acts_as_xapian
http://terra-firma-design.com
http://locomotivation.squeejee.com
http://groups.google.com/group/acts_as_xapian
http://factore.ca/
http://blog.mattenoble.com/
Pagination - http://railsdog.com/

Ruby on Rails: Difference between plugin and gem

Ruby Gem and Plugin are both packaging systems. The main difference in their scope in which they are effective.

1) Gem is system dependent and plugin is application dependent.

2) Installation of gem will available through out all application run on interpretor. where as plugin available only to that application it was installed.

3) gem can be managed using gem command. plugin can be installed only after application is created.

4) gem can be uploaded to new version using command. where as plugins cannot be upgraded, they should be uninstall-ed and installed.


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Tuesday, February 23, 2010

Ruby on Rails : Log : Reducing Log File Size

Rails automatically sets up logging to a file in the log/ directory using Logger from the Ruby Standard Library. Do not confuse this with Log4r, a completely different library. The logfile will be named corresponding to your environment, e.g. log/development.log.

The levels available on the logger are (in ascending order): debug, info, warn, error, and fatal.

The production environment logs at the info level and higher by default. This means that for every request received, messages will be written to the log about the request.

As your traffic increases, the amount of log data can become overwhelming and in some cases, writing the log to disk will begin to impact your server performance.

You can choose to log only at the warn level and higher. To do this, add a line to your environments/production.rb:

config.log_level = :warn

Your log file size will be significantly reduced, with the tradeoff being less visibility into your application server's operation.

More details: http://maintainable.com/articles/rails_logging_tips#reducing-log-file-size


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Ruby on Rails : Convert a String into Time

a="Thu Feb 19 18:16:33 +0530 2009"
=> "Thu Feb 19 18:16:33 +0530 2009"
a=Time.parse(a)
=> Thu Feb 19 18:16:33 +0530 2009

a.day
=> 19
a.year
=> 2009
a.month
=> 2
a.hour
=> 18
a.min
=> 16
a.sec
=> 33



If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Ruby on Rails : Ajax : Running Digital Clock

Step 1: view.rhtml
<%= javascript_include_tag "prototype" %>
<h1>Test periodically_call_remote</h1>
<div id='show_date_time_id' style="background-color: #eee"></div>
<%= periodically_call_remote(:update => 'show_date_time_id',:url =>
{ :action => :show_date_time },
:frequency => 1 )%>

Step 2: ajax_controller.rb
def show_date_time
render :text=>"Now : #{DateTime.now.to_s}"
end


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Wednesday, February 10, 2010

Javascript : Validate file upload

Javascript code:

<script language="javascript">
function Checkfiles()
{
var fup = document.getElementById('upload_filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc")
{
return true;
}
else
{
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
</script>

HTML form:

<form action="#" enctype="multipart/form-data" method="POST" onsubmit="return Checkfiles();">
<input type="file" id="upload_filename">
<input type="submit" value="Go!">
</form>

Or Ruby on Rails form:

<% form_for(@upload, :html => {:multipart => true, :onsubmit=>"return Checkfiles();"}) do |f| %>
<%= f.file_field :filename %>
<%= f.submit 'Create' %>
<% end %>


If you find this useful, would you like to buy me a drink? No matter more or less, it will be an encouragement for me to go further. Thanks in advance!! =)

Tuesday, December 1, 2009

Ruby on Rails : Send Email

1. Configuration

add few lines in config/environment.rb
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = {
:address => "smtp.myserver.com",
:port => 25,
:user_name => "myusername",
:password => "mypassword",
:authentication => :login
}


2. Generating a Mailer

To use Action Mailer, you need to create a mailer model.
$ script/generate mailer UserMailer
exists app/models/
create app/views/user_mailer
exists test/unit/
create test/fixtures/user_mailer
create app/models/user_mailer.rb
create test/unit/user_mailer_test.rb


3. Edit the Model

app/models/user_mailer.rb contains an empty mailer:
class UserMailer < ActionMailer::Base
end

Let’s add a method called welcome_email, that will send an email to the user’s registered email address:
class UserMailer < ActionMailer::Base
def welcome_email(recipient, sender, subject, sent_at = Time.now)
@subject = subject
@recipients = 'no-reply@yourdomain.com'
@from = 'no-reply@yourdomain.com'
@sent_on = sent_at
@body = { :name => recipient, :sender => sender }
end
end


4. Create a Mailer View

Create a file called welcome_email.html.erb in app/views/user_mailer/. This will be the template used for the email, formatted in HTML:
<h1>Welcome to example.com, <%= @name %></h1>
<p>You have successfully signed up to example.com</p>

<p>Thanks for joining and have a great day!</p>

Regards,
<%= @sender %>


5. Invoke the deliver_* method

The arguments passed here will be routed to the mailer model object as well. So to send our email from whatever part of the code we want all we have to do is this:
def welcome
recipient = 'John'
sender = 'Mary'
subject = 'Welcome to Example.com'
UserEmailer.deliver_welcome_email(recipient, sender, subject)

flash[:notice] = 'Email Sent Successfully.'
redirect_to('/people')
end


ActionMailer Class Library : http://api.rubyonrails.org/classes/ActionMailer/Base.html

Thursday, November 12, 2009

Ruby on Rails : Thinking Sphinx : Search Engine (gem)

Sphinx is a very fast search engine that indexes data and provides flexible ways of searching it. Thinking Sphinx allows you to link up your models into Sphinx simply and painlessly -– because let’s face it, searching across multiple fields using SQL is a pain in the neck.

Step by step install Sphinx.

Basic files need to edit and according files to apply the function :
1. /config/environment.rb
2. /config/sphinx.yml
3. /app/controllers/articles_controller.rb
4. /app/models/article.rb
5. /app/views/articles/index.rhtml
6. /app/views/articles/_searchResult.rhtml

1. Add few line to /config/environment.rb
Rails::Initializer.run do |config|
config.gem(
'thinking-sphinx',
:lib => 'thinking_sphinx/0.9.8',
:version => '1.3.3'
)
end

2. /config/sphinx.yml
development:
enable_star: 1
min_infix_len: 1
test:
enable_star: 1
min_infix_len: 1
production:
enable_star: 1
min_infix_len: 1

3. /app/controllers/articles_controller.rb
class ArticlesController < ApplicationController
def SphinxSearch
@articles = Article.search '*book*', :with => {
:created_at => 8.week.ago..Time.now,
}

render :partial => 'searchResult', :collection => @articles
end
end

4. /app/models/article.rb
class Article < ActiveRecord::Base
define_index do
# search from articles db table
indexes title, :sortable => true, :facet => true
indexes author, :sortable => true, :facet => true
indexes type, :sortable => true, :facet => true

# search from publishers db table
indexes publishers(:name), :as => :publishers_name, :sortable => true

# search from books db table
indexes books(:description), :as => :books_description, :sortable => true

end
end

** When you make changes to your Sphinx index structure, you will need to stop and start Sphinx for these changes to take effect, as well as re-index the data. This is all wrapped up into a single task:
rake thinking_sphinx:rebuild
rake ts:rebuild

5. /app/views/articles/index.rhtml
<% form_remote_tag(:url => {:action => 'SphinxSearch'}, 
:update => "resultList") do %>
<%= submit_tag 'Search' %>
<% end %>

<div id="resultList">
<!-- Search Result will be displayed here -->
</div>

6. /app/views/articles/_searchResult.rhtml
<% if articles.length != 0 %>
<% for article in articles %>
Id : <%= article.id %><br>
Author : <%= article.author %><br>
Type : <%= article.type %><hr>
<% end %>
<% else %>
No record found!
<% end %>


Sphinx
http://www.sphinxsearch.com/

Ultrasphinx

http://blog.evanweaver.com/files/doc/fauna/ultrasphinx/files/README.html

Thinking Sphinx

http://freelancing-god.github.com/ts/en/
http://groups.google.com/group/thinking-sphinx

Ruby on Rails : Show items per page in Ajax

In views.rhtml
<script language = "javascript">
function check(pagenum, totalpage){
for(var i=0;i<=totalpage;i++){
if(i==pagenum)
document.getElementById('page'+pagenum).style.border='1px solid #000000';
else
document.getElementById('page'+i).style.border='0px solid #000000';
}
}
</script>

<%= javascript_include_tag "prototype" %>
<%
@articles = Article.find(:all, :limit => 10)
@allarticles = Article.find(:all)
@total = @allarticles.length/10

for x in 0..@total
@num = x+1
%>
<span id="page<%=x%>" onclick="check(<%=x%>,<%=@total%>)">
<%= link_to_remote @num, :url => { :action => "articles_per_page", :id => x },
:update => "article_list" %>
</span>
<% end %>

<div id = 'article_list'>
<%= render :partial => 'article', :collection => @articles %>
</div>

In partial page, _article.rhtml
Title: <%= article.title %><br>
Author: <%= article.author %>
<hr>

In controller.rb
def articles_per_page
@show = ((params[:id].to_i)*10)
@articles = Article.find(:all, :offset => @show, :limit => 10)
render :partial => 'article', :collection => @articles
end
** :offset, starting id to show per page
** :limit, limit data showing

Class Pagination : http://rails.rubyonrails.org/classes/ActionController/Pagination/Paginator/Page.html#M000158
Prototype Helper : http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645
Other source : http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_form_for

Wednesday, November 11, 2009

Ruby on Rails : Array : Remove duplicate item

In views.rhtml
<% 
x = 0
arr_type = Array.new
@articles = Article.find(:all)
for article in @articles
arr_type[x] = article.type
x += 1
end
@type = arr_type.uniq*", "

# Output
@articles = research, research, product, product, research, calendar
@type = research, product, calendar
%>

Ruby on Rails : Simple search engine using Ajax

After type words in the input field and wait awhile, the result will display at the partial page, no need to hit enter.

In views.rhtml
<%= javascript_include_tag "prototype" %>
Search : <%= text_field "article", "title" %>
<%= observe_field :article_title,
:frequency => 1.0,
:update => 'article_list',
:url => { :action => 'search' },
:with => "'search=' + encodeURIComponent(value)"
%>
<div id = 'article_list'>
<%= render :partial => 'article', :collection => @articles %>
</div>

In partial page, _article.rhtml
Title: <%= article.title %><br>
Author: <%= article.author %>
<hr>

In controller.rb
def search
@articles = Article.find(:all,
:conditions => ["lower(title) like ?", "%" + params[:search].downcase + "%"])

if params[:search].to_s.size < 1
@articles = Article.find(:all)
render :partial => 'article', :collection => @articles
else
if @articles.size > 0
render :partial => 'article', :collection => @articles
else
render :text => "Result not found!", :layout => false
end
end
end

** To wider search :
@articles = Article.find(:all, :conditions => ["lower(title) like ? and lower(type) like ?
and number like ?", "%" + params[:search][:title].downcase + "%",
"%" + params[:search][:type].downcase + "%", "%" + params[:search][:number] + "%"])

Prototype Helper : http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645

Tuesday, November 3, 2009

Ruby on Rails : Capitalize the character of Multi Word String

Example code :
<% str = "how_are_you? are you feeling good?" %>

<%= str.split(/\s+/).each{ |word| word.capitalize! }.join(' ') %><br>
<%= str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }%><br>
<%= str.titleize %><br>
<%= str.chars.upcase.to_s %>

Output :
How_are_you? Are You Feeling Good?
How_are_you? Are You Feeling Good?
How Are You? Are You Feeling Good?
HOW_ARE_YOU? ARE YOU FEELING GOOD?