Ruby on Rails is really OOPs based framework. I personally love this framework. I worked on this for many years. Many Ruby lovers are looking to integrate the wordpress with Ruby on Rails. I strongly suggest to integrate wordpress with ROR using XMLRPC APIs. Using following code you can easily add the wordpress into Ruby on Rails Project. Use my following steps:
wordpress XMLRPC api integration with ruby and rails
Note: There are so many XMLRPC APIs provided by wordpress. I given the some simple example here.
First setup wordpress. Login to wordpress admin and enable the XMLRPC.
Go to Settings->writing and enable the XMLRPC checkbox.
Now you can fetch the wordpress posts, pages, tags etc.. using XMLRPC.
Following script is written in Ruby.
[viral-lock message=”Solution code is Hidden! It’s Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.”]
require 'xmlrpc/client'
# build a post
#Use this for reference - http://codex.wordpress.org/XML-RPC_wp , http://codex.wordpress.org/XML-RPC_WordPress_API
post = {
'post_title' => 'Post Title',
'post_excerpt' => 'Post excerpt',
'post_content' => 'this is Post content'
}
# initialize the connection - Change
connection = XMLRPC::Client.new2('http://www.purabtech.in/wordpress3/xmlrpc.php') #Replace your wordpress URL
# make the call to publish a new post
#result = connection.call('metaWeblog.getRecentPosts', 1,'admin','123456') // Get Recent 10 Post
#result = connection.call('wp.getPost', 1,'admin','123456',19) // Get Single Post
#result = connection.call('wp.getPage', 1,'admin','123456',1) // Get Single Page
#result = connection.call('wp.getPages', 1,'admin','123456',10) // Get Pages
#result = connection.call('wp.getPosts', 1,'admin','123456') // Get 10 Posts from wordpress
result = connection.call('wp.getPosts', 1,'admin','123456',1000) // Get 10000 Posts from wordpress
#result = connection.call('wp.newPost', 1,'admin','123456',post) //For New Creating the Post
puts result // Printresult
puts result.length // Printresult
The technique we used was quite a hack as this is something that ActiveRecord wasn’t designed to do but now in Rails 3.0 we have a new feature called ActiveModel which makes doing something like this a lot easier.
Active Model in Rails
Before we get into the details of ActiveModel we’ll first describe the part of the application that we’re going to modify to use it.
The screenshot above shows a contact form that has been created using Rails’ scaffolding. The application has a model called Message that is currently backed by ActiveRecord which means that we’re managing messages through the database. We’re going to change the way this form works so that it just sends emails and doesn’t store messages in a database table.
When you’re thinking of doing something like this it’s always a good idea to first consider your requirements and make sure that you really don’t want to store the data from the form in a database as there are often good side-effects to doing this. A database can act as a backup and also makes it easier to move the message-sending into a queue in a background process. For the purposes of this example, however, we don’t want any of that functionality so we’re free to go ahead and make our model tableless.
The code for the Message class looks like this:
File name: /app/models/message.rb
class Message < ActiveRecord::Base
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
end
Message inherits from ActiveRecord::Base as you would expect a model class to, but as we don’t want this model to have a database back-end we’re going to remove that inheritance. As soon as we do this, though, our form will no longer work as the validators are provided by ActiveRecord. Fortunately, we can restore this functionality by using ActiveModel.
If we take a look at the Rails 3 source code we’ll see the that there are activerecord and activemodel directories. The core Rails team has taken everything from ActiveRecord that wasn’t specific to the database backend and moved it out into ActiveModel. ActiveRecord still relies heavily on ActiveModel for the functionality that isn’t specific to the database and as ActiveModel is full-featured and thoroughly tested it’s great for use outside ActiveRecord.
It we take a look in the directory that contains the code for ActiveModel we can see the functionality that it provides.
We can see from the list above that ActiveModel includes code to handle callbacks, dirty tracking, serialization and validation, among other things. The last of these is exactly what we’re looking for.
The code for validations has the following comment near the top and we can see from it that it’s fairly easy to add validations to a model. All we need to do is include the Validations module and provide getter methods for the attributes that we’re calling validators on.
Now that we know this we can apply it to our Message model.
File name: /app/models/message.rb
class Message
include ActiveModel::Validations
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
end
Message inherits from ActiveRecord::Base as you would expect a model class to, but as we don’t want this model to have a database back-end we’re going to remove that inheritance. As soon as we do this, though, our form will no longer work as the validators are provided by ActiveRecord. Fortunately, we can restore this functionality by using ActiveModel.
If we take a look at the Rails 3 source code we’ll see the that there are activerecord and activemodel directories. The core Rails team has taken everything from ActiveRecord that wasn’t specific to the database backend and moved it out into ActiveModel. ActiveRecord still relies heavily on ActiveModel for the functionality that isn’t specific to the database and as ActiveModel is full-featured and thoroughly tested it’s great for use outside ActiveRecord.
It we take a look in the directory that contains the code for ActiveModel we can see the functionality that it provides.
We can see from the list above that ActiveModel includes code to handle callbacks, dirty tracking, serialization and validation, among other things. The last of these is exactly what we’re looking for.
The code for validations has the following comment near the top and we can see from it that it’s fairly easy to add validations to a model. All we need to do is include the Validations module and provide getter methods for the attributes that we’re calling validators on.
Now that we know this we can apply it to our Message model.
File name: /app/models/message.rb
class Message
include ActiveModel::Validations
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
end
This isn’t enough to get our model to behave as the controller expects it to, though. There are two problems in the create method. Firstly the call to Message.new won’t work as our Message model no longer has an initializer that takes a hash of attributes as an argument. Secondly, save won’t work as we don’t have a database backend to save the new message to.
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(params[:message])
if @message.save
# TODO send message here
flash[:notice] = "Message sent! Thank you for contacting us."
redirect_to root_url
else
render :action => 'new'
end
end
end
We’ll fix the second of these problems first. While we can’t save a message we can check that it is valid, so we’ll replace @message.save with @message.valid?.
File name :/app/controllers/messages_controllers.rb
def create
@message = Message.new(params[:message])
if @message.valid?
# TODO send message here
flash[:notice] = "Message sent! Thank you for contacting us."
redirect_to root_url
else
render :action => 'new'
end
end
We can solve the first problem by writing an initialize method in the Message model that takes a hash as a parameter. This method will loop through each item in the hash and assign the value to the appropriate attribute for the message using the send method.
File name: /app/models/message.rb
class Message
include ActiveModel::Validations
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
end
If we reload the form now we’ll see that we’re not quite there yet, however.
This time the error is caused by a missing to_key method in the Message model. The error is thrown by the form_for method so it seems that Rails itself is expecting our model to have functionality that it doesn’t yet support. Let’s add that functionality now.
Rather than guessing everything that Rails expects the model to have there’s a nice lint test included with ActiveModel that allows us to check whether our custom model behaves as Rails expects it to. If we include the ActiveModel::Lint::Tests module in a tests for the model it will check that the model has all of the required functionality.
The source code for the Lint::Tests module shows the methods that the model needs to respond to in order for it to work as it should, including to_key. We can make our model work by including a couple of ActiveRecord modules. The first of these is Conversion, which provides that to_key method and several others. The other module is the Naming module, but in this case we extend it in our class rather than including it as it includes some class methods.
As well as including the Conversion module we need to define a persisted? method in our model, which needs to return false as our model isn’t persisted to a database. With these changes in place our Message model now looks like this:
File name: /app/models/message.rb
class Message
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :name, :email, :content
validates_presence_of :name
validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
validates_length_of :content, :maximum => 500
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
If we reload the form now it will work again which means that the Message model now satisfies all of the requirements that Rails 3 relies on for a model. If we try to submit the form we’ll see that the validators are working, too.
We’ve only covered a little of what ActiveModel provides in this episode but this should have been enough to whet your appetite and give you a reason to look more deeply into its source code to see what it can do. The code is well documented and structured so if you see something you might find useful then there should be enough information in the comments for that file to get you started using it.
Ruby is very powerful object-oriented language. new Ruby performance improvement. Working with pure Ruby is really fun and interesting to me. I am the real fan of Ruby language.
Ruby performance improvement
I am working Ruby on Rails for around last four years. There is always I am thinking and all ROR developers are thinking about performance of application.
We always compare Ruby on Rails with PHP, Java, Python, dot net. We came to know that where we are lacking in ROR. Just one issue performance and memory issue.
When we got news about Ruby 1.9 is comming with performance improvement of 63%. Yes, It is not a joke. This is really great news for every ROR developers. Ruby 1.9 and Rails 3.0 is the future of internet.
Now I will talk about Ruby Software engineer who developed and worked on the Ruby 1.9.
Masahiro Kanai, who improved the performance of several methods in Ruby 1.9. He is the age of high school, just 17.
This year, Ruby 1.9 by the Fibonacci sequence of operations (multiple-precision addition) is,
Ruby 1.8 is slower than I realized Mr. Kanai is a challenge to freedom of choice camp Ruby faster.
In front of all the participants had a similar problem occurring, Ruby of type String, Array types (structures that may have an embedded data structure type object itself) and some of the faster method, attention collection. Oden’s is known to be well-covered tongue teachers. Ruby continued even after the camp’s efforts to speed up to approximately some methods to remove the macro in a constant loop of 63 percent to about 8 percent of success in speeding. This patch has been adopted by the community of developers Ruby, Ruby has been incorporated into the trunk (October 5, 2009).
many professional engineers and developers, with patience to hold out that the problem is resolved, probably as a programmer in one or two talents.
Ketai that builds skills and career tips for the professional engineer. Interviewers are already familiar with this series, the Mr. Ikuo Takeuchi, Professor Department of Creative Informatics, Graduate School of Information Science and Engineering, University of Tokyo. This time, who undertook the voluntary and discover if training for a talented programmer.
His mentor was Koichi Sasada (ko1). The performances of the methods he worked have been bumped up 63% in maximum, 8% in average. His patches were applied to Ruby trunk in Oct. 5 this year.
What he did for Ruby Performance tuning?
He took unnecessary macro references out from a loop. Masahiro spotted macros below in array.c, string.c, and struct.c were referred every time Ruby checked whether data was hold in a structure or not. Even though data were constants, Ruby saw the macros to judge data’s presence in every loop.
What I say now more… I am really happy and I can say this is the biggest news of 2010 in IT world.
One thing I want to mention here about Ruby on Rails. This thing is in mind of all ROR developers.
“Thank God, No need to look Jruby”
He took unnecessary macro references out from a loop. Masahiro spotted macros below in array.c, string.c, and struct.c were referred every time Ruby checked whether data was hold in a structure or not. Even though data were constants, Ruby saw the macros to judge data’s presence in every loop.
Rails 3 beta by February, Ruby on Rails 3, an upgrade to the popular Web development framework that merges Rails with the alternative Merb framework, is due to be offered as a beta release by the end of this month.
Rails 3 beta by February
According to David Heinemeier Hansson, the founder of the Ruby based web development framework, although a beta of Rails 3 is expected by the end of this month the release may slip into February. Hansson gave the estimated release timing in an article on InfoWorld. If all goes to plan Rails 3 is expected to arrive in the first quarter of this year. Rails 3 is a major reworking of the framework which sees ideas from the alternative Merb framework being integrated in a development process which began in December 2008.
Nginx famous now. We given information for how to host multiple rails site on Nginx. we given the configuration code along with their detailed information.
How to host multiple rails site on Nginx
User following code in Nginx.conf file.. and paste into that file.
#vim /etc/nginx/nginx.conf
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log main;
sendfile on;
upstream mongrel_cluster_example1 {
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
}
upstream mongrel_cluster_example2 {
server 127.0.0.1:3000;
server 127.0.0.1:3001;
server 127.0.0.1:3002;
}
# Load config files from the /etc/nginx/conf.d directory
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name example1.com example2.net;
client_max_body_size 120M;
set $myroot /var/www/html;
if ($host ~* example1\.com$) {
set $myroot /home/example1/public;
}
if ($host ~* example2\.net$) {
set $myroot /home/example2/public;
}
root $myroot;
location ~* ^/(images|stylesheets|javascripts).+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$
{
root $myroot;
}
location / {
if ($host ~* example1\.com$) {
proxy_pass http://mongrel_cluster_example1;
} #if check for domain qa.teenangel ends here
if ($host ~* example2\.net$) {
root /home/rail_project/myproject/public;
proxy_pass http://mongrel_cluster_example2;
} #if check for domain ends here
}
}
}
Every time we need this migration script for our projects
Use following command for Model generate
[siwan@localhost siwan]$ ruby script/generate model UsStates
exists app/models/
exists test/unit/
exists test/fixtures/
create app/models/us_states.rb
create test/unit/us_states_test.rb
create test/fixtures/us_states.yml
exists db/migrate
create db/migrate/20091117115011_create_us_states.rb
[siwan@localhost siwan]$
Open the /db/migrate/20091117115011_create_us_states.rb file and paste following code:
When tried to install mysql gem I got following error
[root@localhost siwan]# sudo gem install mysql
Building native extensions. This could take a while…
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/usr/bin/ruby extconf.rb
checking for mysql_ssl_set()… yes
checking for rb_str_set_len()… no
checking for rb_thread_start_timer()… yes
checking for mysql.h… no
checking for mysql/mysql.h… no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/gem_make.out
To find the mysql path on machine used following command
[root@localhost siwan]# which mysql
/usr/bin/mysql
I tried following command:
[root@localhost siwan]# sudo gem install mysql — –with-mysql-dir=/usr/bin/mysql
I Got the same error
[root@localhost siwan]# sudo gem install mysql — –with-mysql-dir=/usr/bin/mysql
Building native extensions. This could take a while…
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/usr/bin/ruby extconf.rb
checking for mysql_ssl_set()… yes
checking for rb_str_set_len()… no
checking for rb_thread_start_timer()… yes
checking for mysql.h… no
checking for mysql/mysql.h… no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/mysql-2.8.1/ext/mysql_api/gem_make.out
ERROR: could not find gem — locally or in a repository
ERROR: could not find gem –with-mysql-dir=/usr/bin/mysql locally or in a repository
Then I checked the mysql-devel
[root@localhost siwan]# yum list mysql-devel
Loaded plugins: refresh-packagekit
Available Packages
mysql-devel.i586 5.1.37-1.fc11 updates
Then I Installed the mysql-devel
[root@localhost siwan]# yum install mysql-devel
Installed:
mysql-devel.i586 0:5.1.37-1.fc11
Complete!
Then I tried the mysql Gem installing…..I am able to install the mysql gem…
[root@localhost siwan]# gem install mysql
Building native extensions. This could take a while…
Successfully installed mysql-2.8.1
1 gem installed
Installing ri documentation for mysql-2.8.1…
Installing RDoc documentation for mysql-2.8.1…
[root@localhost siwan]#
Juggernaut is the Rails plugin for sending and receiving data in different thread. It gives you real time connection to server and you can implement different ideas work or fulfil your requirement.
Juggernaut uses the eventmachine as a server.
So install the supported gem first.
#gem install json
#gem install eventmachine
#gem install juggernaut
Juggernaut is aims to revolutionize your Rails app by letting the server initiate a connection and push data to the client.
Juggernaut is used for speciallycreating Chat application.
If you want to full details about Juggernaut then go to http://juggernaut.rubyforge.org/
First install the juggernaut to your application using this command. ruby script/plugin install git://github.com/maccman/juggernaut_plugin.git
install the gem : gem install juggernaut
Configure the gem: juggernaut –g juggernaut.yml
Start the Juggernaut server: juggernaut -c juggernaut.yml
(This is not rails server or mongrel server)
In your controller you can use this method to send data to Juggernaut server
Juggernaut.send_to_all(“alert(‘hi from juggernaut’)”)
If you want customize the Juggernaut methods or add new methods then open file: