Showing posts with label ror. Show all posts
Showing posts with label ror. 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]


Wednesday, June 16, 2010

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?

Friday, October 30, 2009

Ruby on Rails : Loop Alphabet A to Z

Print alphabet from A to Z using Array.

Example code :
<%= ('A' .. 'Z').to_a*" " %>

Output :
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Thursday, October 29, 2009

Ruby on Rails : Delete multiple items by check box

In index.rhtml
<% form_for :items, @items, :url => { :action => 'destroy' } do %>
<% for item in @items %>
<%= check_box_tag 'item_ids[]', item.id, false %> <%= item.name %>
<% end %>
<%= submit_tag 'Delete', :name =>'commit', :value => 'Delete',
:confirm => 'Are you sure?' %>
<% end %>

In controller
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
def index
@items = Item.find(:all)

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @items }
end
end

def destroy
i = 0
arr_item = Array.new
@items = Item.find(params[:item_ids])
@items.each do |item|
item.destroy
arr_item[i] = item.name
i += 1
end
@item_name = arr_item*', '

redirect_to(items_url)
flash[:notice] = @item_name + ' was successfully deleted.'
end
line 13: get check box values
line 15 : delete all items
line 16 : store item's name which already deleted
line 19 : item separate with comma, eg: orchid, rose
line 21 : goto index page after items deleted

Ruby on Rails : Replace character

Replace spacing to underscore.
<%= person.firstname %>--> Peterson Gate
<%= person.firstname.gsub(/ /, '_') %>--> Peterson_Gate

Sunday, July 12, 2009

Ruby on Rails : References / Tutorials

Phusion Passenger
Makes deployment of Ruby web applications, such as those built on the revolutionary Ruby on Rails web framework, a breeze.
Nginx - Web server like Apache
Nginx is a free, open-source, high-performance HTTP server and reverse proxy, as well as an IMAP/POP3 proxy server.
Railscasts - Free Ruby on Rails Screencasts
Every week Ryan Bates will host a new Railscasts episode featuring tips and tricks with Ruby on Rails.
Rails Framework Documentation
A framework that includes everything needed to create database-backed web applications according to the Model-View-Control pattern.
Get Started with Ruby
Provide downloads, libraries, reference documentation and TryRuby! in this site.
Core Library
Standard library API, classes, methods.
Ruby on Rails guides
These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.
Tutorials Point
A quick reference guide for Ruby on Rails, Java, Python, PHP, Perl, Ajax, Web development such as HTML, XHTML, CSS, JS, etc.

Forum
Google Ruby on Rails Forum
Nettuts+
Learn Ruby on Rails weekly from Scratch.
Week: 1, 2, 3, 4
Introduction of Ruby on Rails
Get started with Ruby on Rails and breakthrough in lowering the barriers of entry to programming.
Dizzy's Cheatsheets
Tutorials, cheatsheets, tips and more for the RoR framework.