Poetry of Programming

Its about Ruby on Rails – Kiran Soumya

By

Invoker – HTTP Service Manager

Pow is good. Its easy and simple to setup. Recently I faced issue with Pow that suddenly broke due to node update or whatever reason that I couldn’t still figure out. I rebooted the mac, brew updates, node updates, uninstalled and installed it back. But dunno it refused to serve my working development app.

This gave me an opportunity to switch to Invoker. (To be honest, I am not in favor of updating tools or switching to new tools that break our years together work sometimes. We always stick to the version that works until and unless there is a requirement.)

Invoker supports not only Ruby/Rack, but any web-service written in PHP or Python or Java or Django or express.js. So that’s a good news for PHP, Python, JAVA, Django and express.js developers to run web applications on different local domains without /etc/hosts hacks.(+1)

To start off with Invoker, its just three steps process (+1)

gem install invoker
sudo invoker setup
invoker start local.ini

The installation alone requires Ruby >=1.9.3 and it works with any version of app like even ruby 1.8.7 app or any other language app on HTTP service. (+1)

Refer http://invoker.codemancers.com/ if you are migrating from Pow

Before running the last step listed above, you need to make sure to add all your working app paths to local.ini file. Thereby, keeping track of all the apps in one place.(+1)

Here are some useful process management commands (+1)

# List currently running processes managed by invoker
~> invoker list

# Will try to stop running delayed job by sending SIGINT to the process
~> invoker remove app_name

# If Process can’t be killed by SIGINT send a custom signal
~> invoker remove app_name -s 9

# add and start running
~> invoker add app_name

# Restart process given by command Label
~> invoker reload app_name

# Restart process given by command label using specific signal for killing
~> invoker reload app_name -s 9

Last but not least, Logs at one place though you have 3 or 5 or 10 services running at same time. Invoker takes away the pain to look into different terminals for logs of your multiple services.
(+1 * number of apps) 😀

It’s a cool journey of Invoker ! Try it out.

By

Release of Rockdove

Announcing the stable release of my gem Rockdove, version 0.3.1.

So what’s the noise about Rockdove ?

Rockdove is for those applications with a requirement to poll and process every incoming mail from Microsoft EWS 1.0 Mail Server !

It doesn’t just fly away blindly with the mail but parses each mail item for the actual content by stripping off replied or forwarded content. In most of the cases, strips off the signatures too if specified under proper convention with two dashes on top.

Rockdove is installed on our Production Rails App used by around 30k users triggering around 700 mails per day initially and the count seems to be increasing day by day with a number of 100’s…! Its proven to be well tested and stable.

The setting up of this gem is damn easy and pretty clear on github. If there are any queries on this, you can always drop a comment on this blog or raise a issue on github.

I would like to share some use-cases implemented in our Rails App (a enterprise social networking portal), using rockdove:

UseCase 1: Post via Email

Whenever a user emails to our mail server, mail@ewsdomain.com, the scenario is to create a new post in our social networking rails app. Rockdove fetches the mail item, strips off the signature and share the details of the sender and the mail content to our Model which does the App business logic of finding the sender under user list and posting the content under his/her name on the portal. If the sender email doesn’t exist and is not registered, we register those users automatically via email that matches our ewsdomain.com.

Example:

Rockdove::Config.configure do |config|

config.ews_url ‘https://mail.ewsdomain.com/ews/exchange.asmx’

config.ews_username ‘username’

config.ews_password ‘password’

…………………………

end

Rockdove::CollectMail.watch do |rockdove_parsed_mails|
…………………………
rockdove_parsed_mails.each do |email|

# Operation on your rails app Model, ex. Blog
Blog.post_thru(email)
end
…………………………
end

#  Rockdove Accessors one can play with email, ex. email.subject, email.body,

:subject, :body, :has_attachments?, :attachments, :to_recipients, cc_recipients, :date_time_created, :date_time_sent, :from

UseCase 2: Comment to a Post via Email

In a scenario of thread of discussions and users receiving couple of notifications on the post, the user can simply reply to a notification via email and get his mail content posted as a comment/reply to the discussion. Rockdove fetches the mail, pulls in the main content and strips off the previous post replied upon (if the email contains the forwarded content, it will be stripped off too). The content is always retrieved in the text format (supporting markdown syntax).

UseCase 3: Post to a particular User-Group

User can post to group with subject containing the group-name in square brackets ex: [My Community]. Rockdove passes the content of the subject as it is to your Rails app for further processing.

UseCase 4: Email Attachments

Rockdove supports email attachments and saves them to a file based on the path specified by the model in your rails app.

rockdove_email.save_to_file(email_attachment, “#{Rails.root}/assets/images”, filename)

# above code can be refactored as per your app requirements

UseCase 5: Ignore Senders

You can provide Rockdove to ignore mails from a group of sender’s addresses. Rockdove will ignore and even delete those mails from your inbox. ex: postmaster@ewsdomain.com

Rockdove::Config.configure do |config|

…………………………

config.ews_ignore_mails [“postmaster@ewsdomain.com”]

end

 

UseCase 6: Archive Mails that are processed

You can specify Rockdove whether these mails have to be archived on a different folder after processing them or delete them from your inbox.

Rockdove::Config.configure do |config|

…………………………

config.ews_folder ‘Inbox’

config.ews_archive_folder ‘Archive’

end

UseCase 7: Handling OOO and Mail Delivery failures

Your rails app need not worry about how to handle the OOO and delivery failure emails. Rockdove takes care of automatically collecting and deleting those mails even before passing them to your rails app. Whistles to this feature on Rockdove as it has saved a storm of automated out of office mails in the form of posts and comments in our rails app.

By

Rspec to work with Logger

In order to set expectations on what we actually logged during the method call,assign under before(:each)

@test_logger = StringIO.new

controller.stub!(:logger).and_return(Logger.new(@test_logger))

and then match the log output using @test_logger.string

By

Issue with Guard

I came across this error this morning, “The user limit on the total number of inotify watches was reached or the kernel failed to allocate a needed resource. (Errno::ENOSPC)”

Tried Guard ignore path to .git or tried reducing the watch files under Guardfile, but alas! Guard by default handles that ignore path of .git and still it throws the same crazy error…

Googled the issues under Guard gem, then realized that you need to increase the watch count for the current user on your box to fix this.
# Check current maximum
$ cat /proc/sys/fs/inotify/max_user_watches
8192
# Increase the maximum
$ echo 100000|sudo tee /proc/sys/fs/inotify/max_user_watches
Password:
100000
$ cat /proc/sys/fs/inotify/max_user_watches
100000

This increases max_user_watches temporarily.On Ubuntu, to increase at boot, edit /etc/sysctl.conf and add fs.inotify.max_user_watches=100000.

By

Redirect Address/Path with Nginx

Here is the nginx config file which redirects

http://mysite/escapeme/blah =>  http://mysite:3000/blah

user www-data;
worker_processes  3;
error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;
events {
 worker_connections  1024;
}
http {
 include     /etc/nginx/mime.types;
 access_log  /var/log/nginx_access.log;
 sendfile        on;
 keepalive_timeout  65;
 tcp_nodelay        on;
 server {
 listen   *:80; ## listen for ipv4
 access_log  /var/log/nginx_access.log;
 location /escapeme {
 rewrite /escapeme(.*) $1 break;
 proxy_pass http://127.0.0.1:3000;
 proxy_redirect     off;
 proxy_set_header   Host             $host;
 proxy_set_header   X-Real-IP        $remote_addr;
 proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
 }
 }
}

By

SSL/HTTPS on Devise + Rails3

I have seen gems like ssl_requirement, but its too complicated for securing just two pages of user login and sign up.

Referred few blogs and found few useful links for the same:

1> For
# Creating your private key
# Creating your certificate signing request
# Getting your certificate
# Configuring your web server
Refer: http://www.buildingwebapps.com/articles/79189-using-ssl-in-rails-applications
2> For Setting up Rails app with Devise, I have referred this :
http://blog.grow20.com/fun-with-ssl-for-accounts-only

More useful links:
http://blog.dynamic50.com/2011/02/15/ssl-on-wildcard-domains-on-heroku-using-godaddy/
http://www.themomorohoax.com/2010/10/08/using-ssl-in-rails-3

By

Rake Task in Rails 3 on Production ENV

Cannot execute Rake Task in production environment? Does it throws errors of uninitialized objects or refuses to load Model classes?

To execute a rake task for eager loading we require,
config.threadsafe! to be disabled in production which is enabled by default.

But our requirement is to get it disabled only on running a rake task.

Rake already sets a Ruby global: $rails_rake_task

So, in config/environments/production.rb, just say:

 config.threadsafe! unless $rails_rake_task

By

Installing RVM & Git through Proxy

RVM relies on GIT.

So set proxy for GIT first.

*  Set the http_proxy environment
*  Set a proxy command to bypass the connection:
gcc -o connect connect.c
mv connect ~/bin
echo “/home/kiran/bin/connect -H proxy.company.com:6030 $@” >> ~/bin/proxy
chmod +x ~/bin/proxy

echo “export GIT_PROXY_COMMAND=proxy” >> .bashrc

Now try git clone. If it doesnt work, try out the following the command.

export http_proxy=http://<username>:<password>@<proxy_ip>:<proxy_port>

This line below also works like a charm for GIT,

git config --global http.proxy proxy_addr:proxy_port

Once the GIT is configured, for RVM, you need to do one more change for curl,
Set the proxy inside your ~/.curlrc

proxy = proxy.company.com:proxy_port

and now you can install rvm with no issues.

For rvm install thru proxy:

rvm install X --proxy proxy.company.com:proxy_port

If two developers are under the same user-group, we can even clone/copy the .rvm folder within two users without explicit installations.

Some more references:
http://blog.iwkse.homeunix.org/index.php?/archives/9-Git-Basic-setup.html
http://beginrescueend.com/
http://zipizap.wordpress.com/2010/11/02/cloning-rvm-to-other-user-you-can-just-copy-the-rvm-directory/ [This worked for me as well]

By

Handling GIT Conflicts


I am attempting to push when I experience a conflict (ruby-1.9.2-p180)

cts_work/diaspora_cts git:(master)> git push origin master

To git@gitorious.org:diaspora_cts/diaspora_cts.git

 ! [rejected]        master -> master (non-fast-forward)

error: failed to push some refs to ‘git@gitorious.org:diaspora_cts/diaspora_cts.git’

To prevent you from losing history, non-fast-forward updates were rejected

Merge the remote changes (e.g. ‘git pull’) before pushing again.  See the

‘Note about fast-forwards’ section of ‘git push –help’ for details.

 

First, see if the conflict can be automatically resolved:

cts_work/diaspora_cts git:(master)> git pull

error: Your local changes to the following files would be overwritten by merge:

db/schema.rb

Please, commit your changes or stash them before you can merge.

Aborting

 

Git status shows that your state is conflicted:

cts_work/diaspora_cts git:(master)> git status

# On branch master

# Your branch and ‘origin/master’ have diverged,

# and have 2 and 1 different commit(s) each, respectively.

#

nothing to commit (working directory clean)

 

IMPORTANT – If you can resolve the conflict do so (normal procedure), this procedure presumes you wish to write the conflicting updates to a branch.

Reset your tree to just your unmerged updates:

cts_work/diaspora_cts git:(master)> git reset –hard HEAD

HEAD is now at 340a54e changes amde

 

Create a branch, use a name which suggests a conflict:

cts_work/diaspora_cts git:(master)> git branch conflict_stuff

cts_work/diaspora_cts git:(master)> git branch

  conflict_stuff

* master

 

Reset your tree to the prior revision:

cts_work/diaspora_cts git:(master)> git reset –hard HEAD

HEAD is now at 340a54e changes amde

 

Pull the other persons changes:(Do not do git pull but always git fetch + git merge)

cts_work/diaspora_cts git:(master)> git fetch

cts_work/diaspora_cts git:(master)> git merge origin/master

Merge made by recursive.

 app/controllers/sessions_controller.rb            |   21 ++++++—-

 app/models/profile.rb                             |    3 +-

 app/views/layouts/application.html.haml           |   14 +++—

 app/views/people/_profile_sidebar.html.haml       |   15 +++++–

 config/locales/diaspora/en.yml                    |    1 +

 db/migrate/20110226134747_add_columnto_profile.rb |    2 +

 db/schema.rb                                      |    5 ++-

 lib/tasks/profile_update.rake                     |   42 +++++++++++++++++++++

 public/javascripts/application.js                 |    2 +-

 9 files changed, 81 insertions(+), 24 deletions(-)

 create mode 100644 lib/tasks/profile_update.rake

 

Switch back to your branch:

cts_work/diaspora_cts git:(master)> git checkout conflict_stuff

Switched to branch ‘conflict_stuff’

cts_work/diaspora_cts git:(conflict_stuff)> git status

# On branch conflict_stuff

nothing to commit (working directory clean)

 

Push your conflict branch back to the repoistory:

cts_work/diaspora_cts git:(conflict_stuff)> git push origin master

Counting objects: 11, done.

Delta compression using up to 2 threads.

Compressing objects: 100% (8/8), done.

Writing objects: 100% (8/8), 861 bytes, done.

Total 8 (delta 5), reused 0 (delta 0)

=> Syncing Gitorious… [OK]

To git@gitorious.org:diaspora_cts/diaspora_cts.git

   d25e82a..c977122  master -> master

By

Open ID != OAuth

Open ID single sign-on Authentication for consumers

OpenID allows you to use an existing account to sign in to multiple websites, without needing to create new passwords.You may choose to associate information with your OpenID that can be shared with the websites you visit, such as a name or email address. With OpenID, you control how much of that information is shared with the websites you visit.With OpenID, your password is only given to your identity provider, and that provider then confirms your identity to the websites you visit. Other than your provider, no website ever sees your password, so you don’t need to worry about an unscrupulous or insecure website compromising your identity.OpenID is rapidly gaining adoption on the web, with over one billion OpenID enabled user accounts and over 50,000 websites accepting OpenID for logins. Several large organizations either issue or accept OpenIDs, including Google, Facebook, Yahoo!, Microsoft, AOL, MySpace, Sears, Universal Music Group, France Telecom, Novell, Sun, Telecom Italia, and many more.OpenID is the fast, easy and secure way to sign in to websites.Here are just a few benefits to using OpenID.

Accelerate Sign Up Process at Your Favorite Websites:

Most websites ask for an extended, repetitive amount of information in order to use their application. OpenID accelerates that process by allowing you to sign in to websites with a single click. Basic profile information (such as your name, birth date and location) can be stored through your OpenID and used to pre-populate registration forms, so you spend more time engaging with a website and less time filling out registration pages.

Reduce Frustration Associated with Maintaining Multiple Usernames and Passwords

Most web users struggle to remember the multiple username and password combinations required to sign in to each of their favorite websites, and the password recovery process can be tedious. But using the same password at each of your favorite websites poses a security risk. With OpenID, you can use a single, existing account (from providers like Google, Yahoo, AOL or your own blog) to sign in to thousands of websites without ever needing to create another username and password. OpenID is the safer and easier method to joining new sites.

Gain Greater Control Over Your Online Identity

OpenID is a decentralized standard, meaning it is not controlled by any one website or service provider. You control how much personal information you choose to share with websites that accept OpenIDs, and multiple OpenIDs can be used for different websites or purposes. If your email (Google, Yahoo, AOL), photo stream (Flickr) or blog (Blogger, WordPress, LiveJournal) serves as your primary online presence, OpenID allows you to use that portable identity across the web.

Minimize Password Security Risks

Many web users deploy the same password across multiple websites. And since traditional passwords are not centrally administered, if a security compromise occurs at any website you use, a hacker could gain access to your password across multiple sites. With OpenID, passwords are never shared with any websites, and if a compromise does occur, you can simply change the password for your OpenID, thus immediately preventing a hacker from gaining access to your accounts at any websites you visit.Because the focus of most OpenID providers (such as Google, Yahoo and AOL) is in identity management, they can be more thorough about protecting your online identity. Most website operators are less likely to be as dedicated to protecting your identity as the OpenID providers, whose focus is on securely hosting user identities.

OAUTH API Authorization between applications

An open protocol to allow secure API authorization in a simple and standard method from desktop and web applications.

If you’re building…

  • desktop applications
  • dashboard widgets or gadgets
  • Javascript or browser-based apps
  • webpage widgets

OAuth is a simple way to publish and interact with protected data. It’s also a safer and more secure way for people to give you access.

If you’re supporting…

  • web applications
  • server-side APIs
  • mashups

If you’re storing protected data on your users’ behalf, they shouldn’t be spreading their passwords around the web to get access to it. Use OAuth to give your users access to their data while protecting their account credentials.For more on OAuth, refer http://hueniverse.com/2007/10/beginners-guide-to-oauth-part-i-overview/

By

Rails Passenger and PHPmyadmin Issue

After getting passenger up and running successfully on my machine and after many days of work, I have got to install PHPmyadmin. But Rails Passenger doesnt allow the connection to http://localhost/phpmyadmin.

After lot of search, I have got it fixed when I updated the following under httpd.conf:

<LocationMatch “^/phpmyadmin/.+”>
PassengerEnabled off
AllowOverride All
</LocationMatch>
Alias /phpmyadmin “/path/to/phpmyadmin”
<Directory “/path/to/phpmyadmin”>
PassengerEnabled off
AllowOverride All
</Directory>

This works like a charm…

By

How Secured is your Rails App?

What do you prefer in terms of Authentication?

Plugin – Restful Authentication (recommended) – easy to use and you can tweak it according to your requirements.

Build your own authentication. You should rarely need to do this … Restful Authentication is quite flexible.

OpenID – a universal authentication system to avoid use of multiple username and password on the Internet. OpenID is getting quite famous now-a-days.

Access Control : To easily proivde different priviliges to your users. There are a lot of cool plugins available for access control.

Centralized Authentication Server – is used to implement single login/password for your users across multiple application. It can also be used for a single sign-on system. For example, Gmail and Google Reader have a single sign-on between them.

Use Google Authentication API to let your users login using their google username and password.

More Plugins :

Read More

By

Ubuntu 9.10 running in low-graphics mode

After the installation from update manager, and every time I boot up my machine, I get a error with three options out of which I am forced to click OK for “Run Ubuntu in low-graphics mode for just one session” option.

Resolution upon reference from url (http://ubuntuforums.org/archive/index.php/t-1242813.html) for Ubuntu 9.10:

Take a backup and edit xorg.conf file:

sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf_bkp
sudo gedit /etc/X11/xorg.conf

Delete this Section Device:

Section “Device”
Identifier     “Device0”
Driver         “nvidia”
VendorName     “NVIDIA Corporation”
BoardName      “GeForce 8400M GS”
EndSection

And Edit the Section Screen as:

Section “Screen”
Identifier     “Screen0”
Device         “Device0”
Monitor        “Monitor0”
DefaultDepth    24
SubSection     “Display”
Depth       24
Modes “1440×990”
EndSubSection
EndSection

Here we go, no more low graphics mode issues.

By

Windows 7 and ROXIO

I recently got my XPS M1330 notebook upgraded from Windows Vista to Windows 7.It happened that one day I need to burn a CD and found that ROXIO DVD Creator is no more working though I have used it less. I have found the collection of CDs given by Dell and re-installed ROXIO Creator 9.  Thats it ! I made my own Axe on neck. Everytime I boot up my notebook. a pop up near the windows toolbar stating “This driver has got compaitibity issues with windows blah… blah…” and then the following errors appear:Microsoft Visual C++ Runtime LibraryRuntime Error!Program:…ommon Files\RoxioShare\9.0\SharedCom\(application).exeThe application has requested the Runtime to terminate it in an unusual way.Please contact the applications support team for more information – OR – Microsoft Visual C++ Runtime LibraryRuntime Error!Program: C:\Program Files\Roxio\(application folder)\(application name).exeR6025- pure virtual functional call I should say its more than a nightmare. This error keep popping up by freezing my notebook every 10-15 minutes approx. I tried all my ways of uninstalling it by following this support url of ROXIO.http://kb.roxio.com/search.aspx?URL=/content/kb/Creator/000127CR&PARAMS=But No Go !The error continued  for several Days..  Irritated and frustrated, today i just sat for hours to fix it. Finally I did it. Took almost 6 hours to google it and fix it though.I am blogging it to help another “Sufferer” of Roxio.Step 1:  I have got ROXIO installed as many Programs infact using the Roxio Creator 9 CD given by Dell.

  • “Roxio Audio”
  • “Roxio MyDVD”
  • “Roxio Drag and Disc” etc.. with update manager included.

Step 2: Instead of uninstalling the programs through Control Panel remove programs. Uninstall themFrom Program Files -> roxio XXX -> UninstallFollow this support url ->   http://kb.roxio.com/search.aspx?URL=/content/kb/Creator/000127CR&PARAMS= Step 3: I did everything but I couldnt delete Program Files -> Commom Files -> Roxio Shared/Sonic Shared.It says that it is used by some other application. Those are nothing but# RoxWatchTray9.exe# RoxMediaDB9.exe# VideoWave9.exe# MyDVD9.exe# MediaManager9.exe# DiscCopier9.exe# RXLabelCreator.exeStep 4:  I opened Task Manager in Windows 7 , it didn’t showed me any of these processes running. Here lies the main story. Due to which I couldnt delete the Roxio Shared under common files folder which is the root cause of Runtime error Popping up now and then.I even ran to buy Perfect uninstaller Software by reading this :http://www.squidoo.com/uninstallroxioI used that software and got ROXIO uninstalled though.Later I found “Show all process from all users” tab under Task Manager wherein you can end that process of roxioxxx.exe running and easily delete that Roxio shared folder under common files.Great ! those Perfect uninstaller people are earning on Roxio. Kudos to them! Kicks to roxio! and Sorries for other Users (like me)! But dont worry, just try the above steps.

By

Rails 2.3.3 Released

new release of Rails is available – Rails 2.3.3.Among the usual bug fixes, a few new features were added, from the release notes:

  • touch is a convenient method to update a record’s timestamp and nothing else. This is extracted from apps whose models “touch‚” others when they change, such as a comment updating the parent.replies_changed_at timestamp after save and destroy.[..]
  • :primary_key option for belongs_to for broader support of legacy schemas and those using a separate UUID primary key: belongs_to :employee, :primary_key => ‘SSN’, :foreign_key => ‘EMPID’ [..]
  • leaner user-facing encoding [JSON] API.
  • decoding backends for the json and yajl libraries. Both are significantly faster than the default YAML backend.

Meanwhile, the work on Rails 3 continues. Yehuda Katz has posted a few blog entries on the new architecture for Rails 3, as well as lessons learned from refactoring a large code base as Rails.One of the goals of Rails 3 is to bring Merb’s modularity and well defined internal APIs to the Rails codebase; Yehuda’s article on the interface between ActionController and ActionView gives some insight in what’s going on on that front. What becomes clear is that the fusion of Merb and Rails is a major project and is still underway.The work on Rails 3 also has an impact on the development of Merb. A recent discussion on the Merb mailing list addressed the state of Merb 1.1, which was due a few months ago. The current plan is to make sure a smooth migration path to Rails 3 is possible – which, of course, requires to know what Rails 3 architecture will be.With all that said, Merb is still a viable solution for many projects, as Ezra Zygmuntowicz (Merb’s creator) points out:

I’d like to chime in and say that I am still happily building apps with merb, http://engineyard.com/solo is built on merb. I don’t find that there is anything I’m missing or that there are any features or major bugs stopping me from building apps with merb.

For another glimpse at plans for Rails 3, David Heinemeier Hansson’s RailsConf’09 talk is available online.