Monday, March 22, 2010

city_select plugin to display list of indian city in dropdown list

city_select - city_select is the plugin which is basically used for to display the list of indian cities as a drop down list.

The implementation is simple

.script/plugin install git@github.com:abhishekpshukla/city_select.git


I have implemented it using jquery.


$("#user_state").change(function() {var id=('#user_state').attr("value"); $.ajax({url: "update_city/"+id, dataType: "script", type: 'get' })});

NOTE:
. "#user_state" is the dropdown list which contain the list of state name(I have consider the value of user_state as a FULL STATE NAME(for e.g. "Maharashtra") instead of STATE CODE).

Make a render file let say _city_select.erb and inside the controller render the _city_select.erb file and parse the selected state

Feel free to add a city if I am missing one.


Thansk

Thursday, October 8, 2009

Ruby, class and some random stuff - Module, inheritance, MLI

module NowModule

class NowModuleOne

class << self
def find
p "This is intresting!!!"
end
end
end

end

class Parent < NowModule::NowModuleOne
def parentone
puts "This is the parent class!!!"
#parentprotected
#parentprivate
end

class << self
def parentself
puts "This is the self one!!!"
end
end


protected
def parentprotected
puts "This is the protect one!!!"
end

private

def parentprivate
puts "This is the private one!!!"
end

end

#example of inheritance....
class Child < Parent
def childone
Parent.find
p parentone
puts "This is the child class!!!"
end
end

#example of multiple level inheritance
class ChildOfChild < Child
def childofchildone
#the parentone belongs to the parent class which a base class for the Child class..
parentone
end
end

p = Parent.new
c = Child.new
cc = ChildOfChild.new
#cc.childofchildone
c.childone
#c.parentpivate

Monday, September 28, 2009

Connect to database using ruby and ActiveRecord

To get connected you database from your ruby file just include the "ActiveRecord" inside your ruby file.

require 'rubygems'
require 'activerecord'

#establish the connection.
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:database => "database",
:username => "username",
:password => "password",
:host => "localhost"
)

#create a class inherit with you activerecord base class.
class User < ActiveRecord::Base
end

user = User.find(:first)
puts user
Or

class SomeThing < ActiveRecord::Base
set_table_name :users
end

user = SomeThing.find(:first)
puts user

That's It.

Ruby Mysql database connectivity

In this section I am going to tell you how do you get connected your MySQL database using Ruby.

Make sure that you have install mysql adapter
To verify you mysql file go to command prompt type irb -> require 'mysql' if it's return true that means the file is loaded.

Now use your fav editor let say scite.

require 'rubygems'
require 'mysql'

begin
#establish a connection.
mysql = Mysql.real_connect("hostname(e.g - localhost)", "username", "password", "databasename")
result = mysql.query("SELECT * FROM USERS;")
result.each do |row|
row.each do |col|
puts col
end
end
#the col object will return the value from the users table.
# if you want to insert a record. then
mysql.query("INSERT INTO users (email) VALUES ('example@example.com')")
#this is how you can edit delete the records...
rescue Exception => e
puts "I guess something went wrong. #{e}"
ensure
# clone the connection...
mysql.close if mysql
end

Friday, September 11, 2009

bash: cap: command not found

bash: cap: command not found

In this post I'll be talking about how to resolve the “bash: cap: command not found” issue. Even after installing Capistrano we get the following error “bash: cap: command not found” the reason behind this is that the path is not decalred in bash file, so to fix the problem you have to add the following line on code inside bashrc file

Step 1
#go to Terminal
#type
sudo gedit ~/.bashrc

Step 2
#Add the following line at the bottom of the file.
export PATH=$PATH:/home/user/.gem/ruby/1.8
#save and close
# To find the installation of you gem just run the following command
#gem list -d c
# capistrano (2.5.8)
# Authors: Jamis Buck, Lee Hambley
# Rubyforge: http://rubyforge.org/projects/capistrano
# Homepage: http://www.capify.org
# Installed at: /home/user/.gem/ruby/1.8

Step 3
#From command prompt
source ~/.bashrc

Wednesday, September 9, 2009

File Upload using AJAX and jQuery.

File Upload using AJAX and jQuery.

File upload using jQuery is preety simple.

NOTE: please include the jQuery Library afer prototype.js

As you can in the above example I had declared “jQuery.noConflict();” the reason behind this is to abvoid the conflict between jQuery library and prototype.js.

<% remote_form_for :some_random_name, @some_object, :url => {:action => 'testtest'},
:html => { :multipart => true, :id => "upload_form" } do |f| %>


<%= file_field_tag "test" "uploaded" %>
< id="button" class="button" value="Add File" type="button">
< id="save" class="save" value="Upload" type="submit">
<%end%>

Thats it.

Monday, May 25, 2009

How to integrate Comatose CMS in your rails application.

Comatose CMS Yet another Micro CMS, when your client may use to create and edit easily a static pages like privacy policy, terms & conditions, an FAQ, that kind of thing.

Installation of Camotose.
$ ./script/plugin install git://github.com/darthapo/comatose.git
$ ./script/generate comatose_migration
$ rake db:migrate

Once the above mentioned command is executed then configure your route file, at the bottom of your route file paste the below mention syntax
map.comatose_admin
map.comatose_root ''

That it now you to access the Camotose simply type
http://localhost:3000/comatose_admin

You can configure you comatose on your config/environment.rb file, but i'll suggest you to create a comatose.rb inside your config/initializers folder, and insert the following code.

Comatose.configure do |config|
config.admin_title = 'YOUR site name CMS SYSTEM' # it cab anything...
config.admin_helpers = []
config.admin_sub_title = 'Administration Pages'
config.content_type = 'utf-8'
config.default_filter = ''
#config.default_processor = :liquid
config.default_tree_level = 3
config.disable_caching = false
config.hidden_meta_fields = 'filter'
config.helpers = []
config.includes = []
# These are 'blockable' settings
config.authorization = Proc.new { true }
config.admin_get_author = Proc.new { request.env['REMOTE_ADDR'] }
config.after_setup = Proc.new { true }

# Includes AuthenticationSystem in the ComatoseAdminController
config.admin_includes << :authenticated_system

# Calls :login_required as a before_filter
config.admin_authorization = :login_required

end

Wednesday, December 24, 2008

Insert HTML Tag Using Javascript...

The below mention function will be use to insert a div tag along with input field, button when a user clicks on hyper link. Button will be used to hide the selected div. A user can create max 5 div.


function attachFile(id)
{
var count = new Array("1","2","3","4","5")
var hiddenCount = document.getElementById("Cnt").value;
var Comman = 1;


for(var j=1;j<=count.length;j++)
{
if (id == 'remove_' + j)
{
document.getElementById('div_' + j).style.display = "none";
return
}
}
Comman = parseInt(hiddenCount) + Comman;
if (Comman <= 5)
{
var varTag1 = document.createElement("INPUT");
// var varTagRemove = newElement("input",{type:"button",name:"Remove",id:"remove_"+Comman,value:"1"},{onclick:attachFile(this.id)});
var varTagRemove = document.createElement("INPUT");
varTagRemove.type="button";
varTagRemove.value = "Remove";
varTagRemove.id = "remove_"+Comman;
varTag1.type = "file";
varTag1.id = "file_"+Comman;;
var x = document.all;
var br = "br"
if(x)
br = "
"
var varTag2 = document.createElement(br);

document.getElementById("div_" + Comman).appendChild(varTag1);
document.getElementById("div_" + Comman).appendChild(varTagRemove);
document.getElementById("div_" + Comman).appendChild(varTag2);
var rm_test = document.getElementById("remove_" + Comman);
rm_test.onclick = function(){attachFile(this.id)};
document.getElementById('Cnt').value = Comman;

}
else
{
for (var i = 1; i <= count.length; i++)
{
if (document.getElementById("div_" + i).style.display == "none")
{
document.getElementById("div_" + i).style.display = "block";
return
}
}
//ALERT WILL BE CALLED WHEN THE COUNT OF FILE UPLOADER IS 5 AND ALL THE DIV DISPLAY PROPERTY IS
// BLOCK
alert("Limit is over");
}
}

Thursday, December 11, 2008

Ruby: How "send" method works?

Invokes the method identified by symbol, passing it any arguments specified. You can use __send__ if the name send clashes with an existing method in obj.
For example.
Suppose that in you have a three different parameter
1.addnum
2.subnum
3.multinum

depends on the parameter you want to call the method to execute add/subtract/multiply. So what you can do

class Number

def mainfunction(methodname, val1, val2)
#THE BELOW MENTION SEND METHOD WILL CALL ANY ONE METHOD #DEPENDS ON THE FIRST PARAMETER
self.send(methodname, val1, val2)
end

def addnum(val1, val2)
val1 + val2
end

def subnum(val1, val2)
val1 + val2
end

def multinum(val1, val2)
val1 + val2
end
end

num = Number.new
num.mainfunction(“addnum”, 10 , 20) #output => 30

So this is just a very basic example to understand hoe send method work.

Saturday, October 4, 2008

How to enable grant access to remote system for MySQL server?

In a few step you can allow remote system to access your MySQL server. To implement first you will need to configure your my.cnf which which is located at

/etc/mysql/my.cnf [Debian Linux Environment]
OR
/etc/my.cnf [Red Hat Linux/Fedora/Centos Linux]
OR
/var/db/mysql/my.cnf [FreeBSD]

access the file using

sudo gedit /etc/mysql/my.cnf

check for following line
bind-address in which the local ip address is assigned 127.0.0.1
bind-address = 127.0.0.1
So just replace the local ip address with your server ip address e.g. 192.168.XXX.XXX
bind-address = 192.168.XXX.XXX

Thats it now all you need to restart your MySQL server and assign a grant access to remote system.

To restart MySQL server
etc/init.d/mysql restart

To assigned a grant access
GRANT ALL ON user_database_name.* TO remote_user_name@'192.168.x.x' IDENTIFIED BY 'PASSWORD';

Thats it and it is done.. Now
the remote user can access your db..

Tuesday, September 30, 2008

Configuration of phpMyAdmin on ubuntu..

Configuration of phpMyAdmin on ubuntu..
As you know that phpMyAdmin is a database management and adminstration tool. So below is given the installation process of phpMyadmin. Let assume that you have already installed LAMP on ur system.
And incase if you have not installed LAMP then follow the following steps.
1. Open the terminal.
2. install apache [sudo apt-get install apache2].
3. install php [sudo apt-get install php5 libapache2-mod-php5]
4. Once it is installed restart the apache [sudo /etc/init.d/apache2 restart]
5. Install MySQL server [sudo apt-get install mysql-server] and set a password to local system to gets root access.
6. Install MySQL admin [sudo apt-get install mysql-admin]
7. Install MySQL for Apache HTTP Server [sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin]
8. Edit your php.ini file to work your php with MySQL [pico /etc/php5/apache2/php.ini] and add following line [extension=mysql.so]
9. Again restart you apache same command used in point 4.
Now once your LAMP installed all you need to edit your apache2.conf file which is located in '/etc/apache2/apache2.conf' and add the following like
[Include /etc/phpmyadmin/apache.conf] and then restart your apache as given in point 4.
That it and your phpmyadmin is configured.

For accessing you can use the following URL "http://localhost/phpmyadmin/" and if it is configured on server or some other system just changed localhost from domain name.

Your comments are welcome.

How to install RMagick Gem on Ubuntu?

To install RMagick with image magick on ubuntu is very simple you just need to run three commands from your terminal. Just make sure that you have install ruby and rubygem.

Once your ruby and rubygem is install run the following command.
1. sudo apt-get install imagemagick
2. sudo apt-get install libmagick9-dev
3. sudo gem install rmagick

Thats it and Rmagick in installed on your ubuntu environment.

Monday, September 29, 2008

uninitialized constant Gem::GemRunner (NameError)

/usr/bin/gem:23: uninitialized constant Gem::GemRunner (NameError)

After installing ruby and rubygem on Ubuntu i started getting 'uninitialized constant Gem::GemRunner (NameError)' Error, so the solution for this is.
add the following command in your /usr/bin/gem
require 'rubygems/gem_runner'

Thats it and it will start working..

Wednesday, September 3, 2008

add_column new feature :after

Have created a new method, at the time of adding a new column in existing method. The method name is called :after
for ex
add_column :users, :user_info, :string, :after => "email"
when we execute the migration the email will be place just after user_info field in users table.

Monday, September 1, 2008

list of same column name from all the tables.

Hello Friend,
This time i'll tell you something about how we can know which table contains the same column name in a database.

[Note] This query only work in MySQL 5.02 and above

[Important]: - This query can help Ruby developer when they assigned a new project and if the project does not have a E-R diagram, As we never set a foreign key at a database level.
So here is the query

SELECT TABLE_NAME, COLUMN_NAME FROM information_schema.columns
WHERE COLUMN_NAME = user_id' AND table_schema = "test_development"

MySQL Database Dump from shell....

Hello Friends,
This is how we can take a database dump from command prompt.

1. Suppose you want to dump the entire database u can fire following command from cmd prompt...
"test_dump" will be your database name...
Your_location_where_you_want_to_save:\> mysqldump -u root -p test_dump > filename.sql


2. Suppose there are n numbers of table and we want to take a back of only 2 table let say table_abc, table_xyz from the "test_dump" database, so you can fire the below mention query...

Your_location_where_you_want_to_save:\> mysqldump --add-drop-table -u root -p test_dump table_abc table_xyz > filename.sql

Note: -
1. The filename can be anything.
2. Your_location_where_you_want_to_save = can be let say c drive c:\>

Monday, August 25, 2008

ERROR: While executing gem ... (Gem::InstallError)

Many developer had faced the issue at the time of installing rails 2.1.0 by using 'gem install rails'

ERROR: While executing gem ... (Gem::InstallError)

invalid gem format for c:/ruby/lib/ruby/gems/1.8/cache/activesupport-2.1.0.gem

So here is the solutions:

After doing some sort of R&D i found that you will need to download 'activesupport-2.1.0.gem' from http://rubyforge.org/frs/?group_id=570 site and first install activesupport manually. and then run 'gem install rails' from command prompt.

Wednesday, July 9, 2008

divide single word into sentence.

The below mention function will divide the long character word into specific sentence.
for e.g you have a input like "aaaaaaaaaaaaaaaaaaaa" you want this should be divide that means each sentence should contain 5 character "aaaaa aaaaa aaaaa aaaaa".


def word_division(char_length, comment_value)
return nil if comment_value.nil?
chunk_size = char_length
i = 0
chunks = []
while i < comment_value.to_s.length
chunks << comment_value.to_s[i,chunk_size]
i = i + chunk_size
end
return chunks.join(" ")
end

Friday, June 6, 2008

How to send a mail from application

After the configuration of action mailer. Perform the following task.

class Notifier < ActionMailer::Base
def send_email(user_details)
@recipients = "#{user[:email]}"
@from = "xyz@xyz.com"
@subject = "this is testing"
@sent_on = Time.now.utc
@content_type = "text/html"
@body = {}
url = "http://xyz.com/id=12312123"
@body.store('url', url)
@body.store('user', user)
render_message("signup", @body)
end
end


from controller call
def xyz
@user = User.new(params[:user])
if @user.save!
Notifier.send_email(@user)
end
end

and if you want a proper template should be forwarded then in ur view folder/notifier

create a file send_email.rhtml if you are using localization you can call as 'send_email_en.rhtml'
Dear, <%= @user[:login] %>
Welcome to xyz.com

thanks

About ActionMailer and condiguration of action mailer.

ActionMailer allows you to send email from your application, when you generate a action mailer
using following command: -
script/generate mailer Notifier
a action mailer class(inside model folder) and view generate.

Mailer methods have the following configuration methods available.
  • recipients - Takes one or more email addresses. These addresses are where your email will be delivered to. Sets the To: header.
  • subject - The subject of your email. Sets the Subject: header.
  • from - Who the email you are sending is from. Sets the From: header.
  • cc - Takes one or more email addresses. These addresses will receive a carbon copy of your email. Sets the Cc: header.
  • bcc - Takes one or more email address. These addresses will receive a blind carbon copy of your email. Sets the Bcc header.
  • sent_on - The date on which the message was sent. If not set, the header wil be set by the delivery agent.
  • content_type - Specify the content type of the message. Defaults to text/plain.
  • headers - Specify additional headers to be set for the message, e.g. headers ‘X-Mail-Count’ => 107370.
Configuration
1. First you need to configure action mailer with your application.
open environment.rb file or you can write it in a production/development file also.
after the 'Rails::Initializer.run do |config|' block
paste the below mention code

ActionMailer::Base.raise_delivery_errors = true #You may also turn exception raising on and off.
ActionMailer::Base.delivery_method=:smtp
ActionMailer::Base.smtp_settings = {
:address => "smtp.yourserver.com",
:port => 25,
#:domain => "www.mywebsite.com"
:user_name => "username",
:password => "password",
:authentication => :login # :plain, :login or :cram_md5
}
:domain is the name sent to the SMTP server during the handshake. It will be used to form the first “Received:” header, which spam filters usually check.