Jul 25

We have been using  PostgresSQL  in our new product Quiz Stack.

Quiz Stack is a SAAS based  product. Which can  conduct,manage,analysis quizzes.We are using rails and postgresql as our backend.It’s subdomain app and hence we decide to use postgresql schema based approach for storing/querying data.

While working on one of the feature It was needed to draw some random fixed questions for each user.So each user has different order of questions which  is maintain for each specific user.

In Mysql it’s called field function to achieve this ,unfortunately there isn’t  anything as of I know in PostgresSql or is it ? :)

Well we can obviously write a function which can help you do the same.Let’s the function name be sortbyid. 

Following code snippet is a function definition

CREATE OR REPLACE FUNCTION sortByID(anyelement, VARIADIC anyarray) RETURNS BIGINT AS $$
				SELECT n FROM (
   			 	SELECT ROW_NUMBER() OVER () AS n, x FROM unnest($2) x)
   			 	 numbered WHERE numbered.x = $1;
			$$ LANGUAGE 'SQL' IMMUTABLE STRICT;

So here how I get the result from Question table  for 3 record with order or id as 2,1,3

Continue reading »

Tagged with:
Jul 22

I was working with Refinery cms  some times back.I want blogging facility to my CMS. Refinery has various engine which can easily plug and play including blogging.

Blog Engine doesn’t facilitate with searching facility default,but it’s easy to add searching facility.

Following Snippet will help you to do this.

# app/models/refinery/blog/post.rb
module Refinery
  module Blog
    class Post < ActiveRecord::Base
      ........
      .......
      class << self
         ......
       # Considering   "refinery" is a prefix so table name is refinery_blog_posts
 
        def search(search_string="")
          Post.includes(:categories,:tags).live.where(
              "refinery_blog_posts.title like (?) or refinery_blog_posts.body like (?) 
              or refinery_blog_categories.title like (?) or tags.name like (?)",
              "%#{search_string}%","%#{search_string}%","%#{search_string}%","%#{search_string}%")
        end
      end
    end
  end
end

Now if you want you can add search method in controller or you can use index method for this.
Following Snippet will help us to search a blog posts.
Continue reading »

Dec 28

It’s 5 in the morning and i am tired and its a possibility that i may be writing a long post, Last night i asked my self what is it that i have learned in the las t couple of months and out of nothingness i rememberd a VIDEO CHAT APPLICATION which my friend Viren and I worked on. I thought it might be useful for some of you.

When we started, we didnt have enough knowledge where to begin with and had time constraints.We came across solutions like Red5,ErlyVideo.
Now out problem was that out client had to be in flash or java applet, we we tried lots of things and the mother solutions of all problems was yet released, HTML5.

When we started, we didnt have enough knowledge where to begin with and had time constraints to meet. We came across solutions like Red5,ErlyVideo. Now our problem was that our client had to be in flash or java applet. So we tried working around many solutions. HTML5 was months away from its release.

we are looking into other HTML5 Features and we get awesome HTML5 web socket support so we thought let’s get some hands on it.

So we think let’s build pubsub chat application, after Googling we got couple of solution.but we want to build own i have choice between nodejs and EventMachine.we have choose EM to quick start.

So we are ready,
We go through HTML5 Web Socket API,and tutorial so basically it’s a technique for two-way communication over one (TCP) socket, a type of PUSH technology.
So it has mainly three events

  1. onopen: When a socket has opened
  2. onmessage: When a message has been received
  3. onclose: When a socket has been closed

More info regarding HTML5 Web Socket you can visit Nettuts, HTML5Demo.
lya Grigorik has written awesome library,and article on it so i don’t go in much detail.

Steps we are following

  • When User is connected onopen event is fired and  we create one default connection and add to pool of channels,it’s used for mainly notification purpose
  • Continue reading »

Tagged with:
Dec 27

Hey all,
In Previous article i have given short bio of ruby daemon using daemon kit.
In this post i am writing about how to manage daemon,how to start/stop a daemon from any directory.

We can start a daemon using following way.
Go to the directory and give the command.

./bin/mydaemon

or

./bin/mydaemon start

(You know the difference right; To run it in foreground or background respectively.)

But consider this possibility, what if you didn’t want to go to the directory where the daemon is located and start it.

/home/mysystem/mydaemon/bin/mydaemon

or

/home/mysystem/mydaemon/bin/mydaemon start

Now you might be thinking why you will want to do that, let me say such conditions does arise (when you want monit to watch over it and restart it when it goes down.)

Usually this would work with ease if you are not using a bundler, however if you are using it then this would be something that you would get to see.

Continue reading »

Tagged with:
Dec 22
Hey all,
Many of us knows what daemons are in linux. These are processes or programs that run in background with little or no user intervention.
Now we can write daemons in ruby too. And for doing so we can use Daemon-Kit(https://github.com/kennethkalmer/daemon-kit).
Now the daemon can do the task continuously or do it at particular interval of time or do it depending on a particular event.
Daemon-Kit provides a skeleton to write these different types of daemons with the help of differnt types of generators.(XMPP bot,AMQP client,Nanite agent,Cron-style,ruote remote participants). Of these XMPP and AMQP are event based and amqp is specifically based on queuing system, and Nanite agent gives a nanite structured daemon while Cron-style is used to write daemons that perform certain task at particular interval amount of time.
First install the gem daemon-kit
gem install daemon-kit
For viewing the help of daemonkit you can give the command,
daemon-kit -h
Now to build a simple daemon which would use a default generator you can use,
daemon-kit mydaemon
For building a daemon with a generator you can use,
daemon-kit mydaemon -i amqp</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">daemon-kit mydaemon -i cron
Now for starting the daemon first you go into the daemon directory and then give the command,
cd mydaemon</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">./bin/mydaemon
which would start the daemon in foreground which is used for testing if everhting is working.The daemon would die as you close the terminal.
To purely daemonize it you can use
./bin/mydaemon start
This would start the daemon in daemonized form and would continue to run in background till any untoward exception occurs.
To stop the daemon running in background you can use the commnad
./bin/mydaemon stop
Now the basic tree structure of a daemon would be something similar to this.
</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">my_cron_daemon</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── bin</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── my_cron_daemon</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── config</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── arguments.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── boot.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── environment.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── environments</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   │   ├── development.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   │   ├── production.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   │   └── test.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── post-daemonize</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   │   └── readme</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── pre-daemonize</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│       ├── cron.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│       ├── readme</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│       └── safely.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── Gemfile</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── lib</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── my_cron_daemon.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── libexec</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── my_cron_daemon-daemon.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── log</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── Rakefile</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── README</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── script</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── console</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── destroy</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── generate</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── spec</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── my_cron_daemon_spec.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   ├── spec_helper.rb</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── spec.opts</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── tasks</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">│   └── rspec.rake</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">├── tmp</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">└── vendor</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">
The pre-daemonize folder consists of all the files that are required before the daemon starts. The cron.rb can be used to require all the gems that are needed for the daemon.
The my_cron_daemon.rb in lib folder is automatically loaded when the daemon starts. Additonal ruby files can be created in the lib folder and can be required from the cron.rb in pre-daemonize for utilization.This can be done as,
excluded_files = [File.join(DaemonKit.root, 'lib', "my_cron_daemon.rb")]</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">(Dir.glob(File.join(DaemonKit.root, "lib", "*.rb")) - excluded_files.flatten).each{|f| require f}
This is done because my_cron_daemon.rb in lib is automatically loaded and requiring it multiple times might cause issues.
The post-daemonize folder is used to place those files that needs to be loaded after the daemon starts.
Similarly a yml file(e.g config.yml) which holds all the configuration setting can be created in the config and loaded into the daemon using,
CONFIG = DaemonKit::Config.load("config.yml")
Here CONFIG can be used anywhere in the daemon later on to access the required configuration.
Now you can also add ruby files that connect to a particular database and query data by putting those in lib. These files would have a structure similar to the ruby files in models of rails application.
As for the database connection you can put these pieces of code in cron.rb in pre-daemonize which establishes the databse connection,
ActiveRecord::Base.configurations = CONFIG[:database_configuration]</div>
<div id="_mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow-x: hidden; overflow-y: hidden;">ActiveRecord::Base.establish_connection(CONFIG[:database_configuration])
where “database_configuration” is placed in the config.yml
Now we can also have the daemon as a request-response serving program similar to a rack-server, This can be done by using eventmachine.
Daemons are a difficult to debug. Because they can just cause  your program to fail when a request comes in. Normally we write a code in a normal Ruby program and run it to test all the functionallity and then put it within the daemon. This helps in ensuring that your logic is proper. For further debugging I use a lot of puts statements when coding later switching to DaemonKit.logger.info or .debug to dump the statements to the log.
DaemonKit.logger.info "I am the DaemonKit logger info"
Here is a link to a basic daemon which is based on default,cron generator.
https://github.com/kelvink/My-Basic-Daemon
https://github.com/kelvink/My-Cron-Daemon
Also here is a link for the daemon to work as a rack server using evenmachine.
https://github.com/kelvink/My-EM-Daemon
Thus we can have a ruby daemon which perform specific task as required and when required.

Hey all,

Many of us knows what daemons are in linux. These are processes or programs that run in background with little or no user intervention.

Now we can write daemons in ruby too. And for doing so we can use Daemon-Kit.

Now the daemon can do the task continuously or do it at particular interval of time or do it depending on a particular event.

Daemon-Kit provides a skeleton to write these different types of daemons with the help of differnt types of generators.(XMPP bot,AMQP client,Nanite agent,Cron-style,ruote remote participants). Of these XMPP and AMQP are event based and amqp is specifically based on queuing system, and Nanite agent gives a nanite structured daemon while Cron-style is used to write daemons that perform certain task at particular interval amount of time.

First install the gem daemon-kit

Continue reading »

Tagged with:
Oct 24

Just quick post how to use acts_as_flying_saucer with rails 3.1 and Heroku.

I was testing acts_as_flying_saucer with rails 3.1.It is working fine so far.
but when i have added external style sheet it was hanging on dev mode.
and later on i figure out it is external style sheet causing an issue.
So i precomplied css and then try to generate pdf it is working.
Now it is time to test on heroku.
I am using cedar stack and ruby 1.9.2 after precomplied step pdf.
By default pdf is generated on system /tmp directory.
In heroku we can set application tmp path to generate pdf i.e ./tmp

I was testing acts_as_flying_saucer with rails 3.1.It is working fine so far,but when i have added external style sheet it was hanging on dev mode rails is hanging

After litte bit of googling  i figure out it is external style sheet causing an issue because of asset pipeline and thread issue for serving static file mainly in dev mode.

So i simply pre complied css or we can manually (actual full path) or manipulate asset path .after this PDF is generated properly.

Now it is time to test on Heroku.I am using cedar stack and ruby 1.9.2 after pre complied step.

Now point tmp directory to application tmp directory.

ActsAsFlyingSaucer::Config.options = {:tmp_path => "./tmp"}
Tagged with:
Oct 24
It’s about more than 6 months i haven’t written any post.
Why ?
Recently join new organiztion,
Can’t get time because we are working almost more than 10 to 12 hr day with messy code.
So we are spending more time to refactoring and optimising code,and scaling application also.
Now i started making my time to writing.
In my current organization we are generating various Pdf report.
We are using prawn but now we are switching to  acts_as_flying_saucer.
So there are couple of challenges i have faced
1) XHTML code is not proper
2) Special character in html
Solution
Cleanup Html code
I am using tidy library clean up html code.
By passing :clean=>true it will cleanup html befor generating pdf.
3) Send PDF as email
Solution
Generate PDF on server and do some processing like attached to mail.
:send_attachment => true it will generate pdf and return path of pdf file then do some processing.
So couple of new feature is added to acts_as_flying_saucer
1) Clean up  html by passing :clean=>true
2) Generate pdf on server (locally) by passing :send_attachment=>true
3) acts_as_flying_saucer is also working with rails 3.1 (precomplie asset) and heroku.

It’s about more than 6 months i haven’t written any post Why ?

because recently join new organization, and can’t get much more time , we are working almost more than 10 to 12 hr day with messy code.So we are spending more time to  refactoring and optimizing code,and scaling application.😥

In my current organization we are generating various PDF report.We are using prawn but now we are switching to acts_as_flying_saucer.

So there are couple of challenges i have faced

  1. XHTML code is not proper
  2. Special character in html

Solution: Cleanup Html code

Continue reading »

Tagged with:
Aug 30

Well long break,Let me guess It over 3 month since I wrote my last post. I’ve been kind of  busy lately not manage to dedicate much time to thing that I do.

Rails 3.1.0 is been in picture for a quite a while a now and major feature that been included in Rails 3.1.0 is asset pipeline and pre-processor.

For those is who aren’t aware of Rails 3.1.0 asset pipeline and pre-processor there is a very good article on rails guide and recently Ryan Bates introduce a screencast on Rails 3.1.0 asset pipeline.

I’m not here to talk about asset pipeline you can get it all if you just googled it.

So what I’m here upto then ? :)

Well ever since I was made aware of what asset pipeline  and pre-processor more importantly pre-processor ,it always trilled me of using a custom pre-processor .

As you all know that Rails 3.1.0.rc1 is bundle with coffee-script and sass support. In your asset folder you may find js and css file that look something like this “*.js.coffee” , “*.css.scss“. Now you can add a chain of pre-processor that just look like this “*.js.coffee.erb” , “*.css.scss.erb

The post is all about chaining your own pre-processor just as above something like “*.js.coffee.mustache

Mustache (Mustache is taken just for example here you can use your own) because I been in love with it ever since I explored it . So how to accomplish this .

Stay with me as I will show how ?

Firstly you need to be aware of Sprockets and Tilt library

First the code

Continue reading »

Feb 02

There are various library for manipulating image,one of them is GD library.
In this post i quickly show how to resize an image or generate thumbnail of image using GD2.

Basic steps as follows

  1. First import image
  2. Resize an import image to desired size
  3. Export Image to desired file

above code is extracted from rchart.

Tagged with:
Jan 26

I have to admit this . I always fall in love with RAILS each day as I explore it to know how a complex problem can be handle with great ease and with minimum amount of code.

That what made me write this post on " Conditional Get Request."
For those who aren’t aware of it let me give them some insight in it.

Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn’t changed since the last request and can be safely pulled from the browser cache.

They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to pass back and forth both a unique content identifier and thetimestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.

Enough of talk now its  time for the action (Way to achieve it in Rails)

class UsersController < ApplicationController
 def show
   @user = User.find(params[:id])
    fresh_when :last_modified => @user.last_updated_at ,:etag => @user
 end
end

That it done

Now let check the logs to find, does it actually asking browser to read from its cache.

First time the page will completely render but any subsequent query for the same page will ask the browser to display from its cache(browser cache) (until modified).

Here my log :-
Conditional GET-Log
Other way to achieve the same is.

 def show
   @user = User.find(param[:id])
    if stale?(:last_modified_at => @user.updated_at,:etag => @user)
      repsond_to do |format|
        format.html
      end
    end
end
 def show
   @user = User.find(params[:id])
    response.last_modified = @user.updated_at
    response.etag = @user
    if request.fresh?(response)
      head :not_modified
    else
      respond_to do |format|
        format.html
      end
    end
 end

The Following Code should give you same result as above

That it , thats all it take to get " Conditional GET " working in Rails. Wasn’t I right when I said that I fall in love with Rails each day.

Usage :-

Now most of you  might be wondering where can they employ this technique or when should they use it

My Answer to them is think of Conditional Get a kind of Caching Mechanism ( after that what browser is doing for you)

Now suppose you have a method in controller that make large number of Database queries or ERB template that render a lot of contents on per requests .Wrapping the same with " Conditional GET " can simply do a lot of good.

That it enough on " Conditional GET " . Hope the post help you in some way or other.

Thank You .

preload preload preload