Calling expire_fragment within rails console

Today i want to expire a fragment cache in haml view:

-cache('taxonomy') do

So I enter in rails c production, but I found Rails.cache.exists?(‘taxonomy’) returned false.

expire_fragment doesn’t exist in ActionController::Caching::Sweeper. It can be found in ActionController::Base. The sweeper class uses method_missing to call the method from a controller instance.

ActionController::Base.new.expire_fragment(‘taxonomy’, options = nil) 

That’s why everything was fine when I used to expire through controllers and nothing happened when everything was called from an observer class or so, I just needed a controller instance and it worked.

def expire_cache_for(deal)
  @controller ||= ActionController::Base.new 
  expire_fragment('taxonomy')
end

Rails: Calling Stored Procedure and read OUT variables in Sequel

Very recently stumbled upon a situation, where I need to call a Oracle DB Stored Procedure and also need to read the OUT variables in one of our Ruby on Rails application or in simple words read the output after calling stored procedure in one of our Rails application.

To add to our dismay, it’s not ActiveRecord connection but we were using Sequel library. Sequel do support the Oracle library and it’s very silimar to AR ORM and thanks to this wonderful gem that works out-of-the-box. But it’s not straight forward to call Stored PROC and read the OUT variables and there is next to no documentation to process OUT variables from our stored PROC

DB specific SQL can be executed using “execute” method and almost all the DB adapters provide this method. But question remains the same how to read the OUT variables and I have never called a Stored Procedure ever in my life. It seems an interesting problem to solve and answer may be hidden somewhere in the code but no documentation.

Let’s try to read the OUT variables in different ways taking one step at a time:

1. Create a sample procedure which takes one integer and one string as input and returns integer multiplied by 2 and UPPERCASE of string

create or replace
PROCEDURE MYPROC 
(
 age IN NUMBER 
, name IN VARCHAR2 
, fathers_age OUT NUMBER 
, capital_name OUT VARCHAR2 
) AS 
BEGIN
 fathers_age := age*2;
 capital_name := UPPER(name);
END MYPROC;

 

2. How to call using SQL and read OUT variables (in SQLDeveloper)

 var age number
 var naam varchar2
 var papa_age number
 var bada_naam varchar2
 exec :age := 20
 exec :naam := 'akshay'
 exec MYPROC (age => :age, name => :naam, fathers_age => :papa_age, capital_name => :bada_naam)
 print papa_age
 print bada_naam

OUTPUT

PAPA_AGE
--
40
BADA_NAAM
------
AKSHAY

 

3. How to call it using ActiveRecord using Ruby OCI8 GEM

cursor = ActiveRecord::Base.connection.raw_connection.parse("BEGIN MYPROC(:age, :name, :fathers_age, :capital_name); END;")
cursor.bind_param(:name, 'akshay')
cursor.bind_param(:age, '20')
cursor.bind_param(:fathers_age, nil, Fixnum)
cursor.bind_param(:capital_name, nil, String, 20)
cursor.exec()
p cursor[:fathers_age], cursor[:capital_name]

OUTPUT

1.8.7 :125 > cursor.exec()
 => 1
1.8.7 :126 > p cursor[:fathers_age], cursor[:capital_name]
40
"AKSHAY"

 

4. How to call it using Sequel Database Toolkit.

require 'sequel'
db = Sequel.connect(:adapter=>'oracle', :host=>'localhost', :database=>'db_name', :user=>'test', :password=>'test')
db.execute("begin MYPROC(:age, :name, :fathers_age, :capital_name); end;", {:arguments => [[20, "integer"], ["akshay", "string"], [nil, "integer"], [nil, "string"]]}) { |cursor| [cursor[3], cursor[4]] }

OUTPUT:

1.8.7 :158 > db.execute("begin MYPROC(:age, :name, :fathers_age, :capital_name); end;", {:arguments => [[20, "integer"], ["akshay", "string"], [nil, "integer"], [nil, "string"]]}) { |cursor| [cursor[3], cursor[4]] }
 => [40, "AKSHAY"]

 

This is important to note, oracle adapter inside sequel uses the Ruby OCI8 gem but the implementation is not straight forward as in the case of ActiveRecord.

To further understand how the variables are bound and how are we reading out the OUT variables, I recommend to read the code written inside the ORACLE adapter of SEQUEL gem.

Hope this bit of information is useful and many thanks to  for such a great sequel gem. Happy Hacking 🙂

 

 

Smartphone Native Application using Ruby in 30 min

Building a Smartphone (Android, iPhone, BlackBerry etc) app using ruby

Google Android
iPhone Logo
BlackBerry Logo


RhoMobile Framework


Rhodes

Rhodes is an open source framework to rapidly build NATIVE apps for all major smartphone operating systems (iPhone, Windows Mobile, RIM, Symbian and Android). These are true native device applications (NOT mobile web apps) which work with synchronized local data and take advantage of device capabilities such as GPS, PIM contacts and camera.

Yeah! Its in Ruby 🙂

  • support for ALL smartphones
  • synchronized offline data
  • a Model View Controller (MVC) framework
  • an Object Relational Manager (ORM) to avoid direct SQL coding
  • the mobile Ruby
  • a hosted development service
  • scaffolding to quickly build the app

Setup (Android)

  • gem install rhodes
  • Java JDK latest version is needed for Android. Make sure its installed. Test by typing $javac -version in your terminal
  • Download Android SDK (for linuxMac OSWindows) and extract at a convenient location.
  • Change in your ~/.bash_profile(Mac) and ~/.bashrc(Linux) to add
    export PATH=/path-to-android/tools:$PATH
    export ANDROID_HOME=/path-to-android
  • typing $android in the terminal shall start Android SDK and AVD Manager
  • once ACD manager started install the latest packages under “Available packages”, it will take a while to install
  • Once installed they will list under “Installed Packages”
  • else installation follow these instructions to install Android SDK starter packages, and change the PATH environment variable for sure
  • Download and install Android NDK (Win, Mac OS, Linux) and export your path same as above

Setting up rhodes
Now we need to link our rhodes installation to the SDK and eclipse.
$rhodes-setup
You’ll be prompted with questions – my answers are below:
  • JDK path: /Library/Java/Home
  • Android SDK path: /opt/androidSDK/
  • Android NDK path: /opt/androidNDK/
  • the remainder of the questions related to Windows and Blackberry: (left blank)

HelloWorld Program

rhogen app HelloWorld

cd HelloWorld

rake -T  (will list all the rake tasks for all supported smartphones)

rake run:android (it will build, install and launch the HelloWorld Program)

Of course it will be blank and its just the start. Go to launcher you will be able to see your HelloWorld application with rhodes default icon.

My Contacts

This is fine, but what about ruby and MVC framework? Open your latest HelloWorld in your favorite editor(textmate etc). You will find an “app”, “app=>helpers” folder much like rails “rhoconfig.txt” => configuration settings

$ rhogen model Contact name, email, phone

Generating with model generator:

[ADDED]  app/Contact/index.erb

[ADDED]  app/Contact/edit.erb

[ADDED]  app/Contact/new.erb

[ADDED]  app/Contact/show.erb

[ADDED]  app/Contact/index.bb.erb

[ADDED]  app/Contact/edit.bb.erb

[ADDED]  app/Contact/new.bb.erb

[ADDED]  app/Contact/show.bb.erb

[ADDED]  app/Contact/contact_controller.rb

[ADDED]  app/Contact/contact.rb

[ADDED]  app/test/contact_spec.rb

You can see the controller, model and view files similar to Rails frame work.

Change the

start_path = ‘/app/Contact’ (in rhoconfig.txt)

$ rake run:android

Your application will relaunch and you can click “new” button to add new contacts and edit and delete them. So basic CRUD functionality is available much like rails and ready to go.

I hope you will find this ready to go tutorial very helpful to start of your application on any smartphone using Rhodes framework.

Stay tuned for more!

Encodings in a MultiLingual Web Application

Encodings in a Web Application

Tools: MySQL as a DB, Ruby/Python/PHP as a Language

Problem: If you are working on multi-lingual web application, and need to store them in database. One will surely encounter with the encodings issue. In Ruby1.8.6 I haven’t found anything promising that can clearly state what is the encoding of a String/data. To achieve the same is easy and explained very clearly for other languages and I feel Python’s support for encodings is the best and very  clean and self explanatory.

Things to remember:

  • MySql Database and each table must be created in UTF-8 format. By default its latin and it was very annoying to change at a later stage after realizing it.
CREATE DATABASE <database name> DEFAULT CHARACTER SET utf8
  • Make sure all data that is being stored in DB and in Tables is in UTF-8 format, else convert it will talk in about it in a while.
ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
  • If struggling in displaying or storing characters in proper encodings, make sure you have set encoding: utf8 in your database.{yml/php}. e.g.
development:
  adapter: mysql
  database: db_name
  username: username
  password: password
  host: localhost
  encoding: utf8

UNICODE is not UTF-8

I will try to be succinct to explain UTF-8 is not Unicode or Unicode is not UTF-8. I don’t remember where I read about it but this expert advice helped me a lot to differentiate between Unicode and UTF-8. This post has explained Unicode philosophy.

As the computer reads the characters on user input, read them as UNICODE which is in Computer  Format and is unique . Once you try to store it in a variable or in DB then Encodings comes into picture and then it depends in what encodings you are saving. If its UTF-8, things are fine and as expected if its not, it may cause some trouble.

Unicode is a system that provides a unique number for every character of a language, no matter what the language.

The mapping of “0x40” for the letter “g” is called an encoding. The value is encoded as the letter. Depending on the encoding, “0x40” could be the letter “g” (as in many North American and European encodings) or the Bangladeshi “Ù„” or the Georgian “პ”.

Python way is the easiest and preferred:
1
t = "Héllo"; x = unicode(t); str = x.encode("utf-8")

To detect String/Text encoding in Ruby?

Where was I struck?

Characters (Cyrillic/Latin/Funny) are stored wrongly in database and need to changed and stored in utf-8, after analyzing what is the current encoding of the stored text.

How to do it:

Certainly there are ways to be solved by mysql itself, but none of them worked out in my case or I may need to learn more mysql. At the same time I felt more interested how to do it Ruby way!

So here is a way I tried out and it worked very well and helps me anytime I need to know about encoding of a text/string or need to convert in any format.

First, Install the chardet gem by issuing the following command:

 $ sudo gem install chardet

Then in irb:

 require 'rubygems'
 require 'UniversalDetector'
 p UniversalDetector::chardet('Ascii text')
 p UniversalDetector::chardet('åäö')
 p UniversalDetector::chardet("Déjà vu")

The respective output from this example is:

{"encoding"=>"ascii", "confidence"=>1.0}
{"encoding"=>"utf-8", "confidence"=>0.87625}
{"encoding"=>"utf-8", "confidence"=>0.7525}

Now to convert it into desired format:

 require 'chardet'
 require 'rubygems'
 require 'UniversalDetector'
 encoding = UniversalDetector::chardet(str)["encoding"] #detects the str encoding
 Iconv.iconv("UTF-8", encoding, str).to_s  #converts the current encoding to UTF-8 of the present string

I shall love to hear your suggestions/feedback if it doesn’t work out or if it helps you and save your nights work to research on how to handle encodings

Auto Date: JavaScript based Autocomplete Date selector

Input Date Known Interface

If we talk about the date interfaces on web. There are only couple of them with easy customization as per use-case.

  • Calendar JS plugin

    Calendar image

    Calender based JS plugin http://www.dynarch.com/projects/calendar/

  • Seperate DD MM YYYY
  • Full Calendar

One might have used some decent date interfaces on some Desktop clients e.g. Omnifocus (Mac) is one having powerful date time selector with sleek interface. To be true, after using it we at EnTrip felt to design something for WEB2.0, something sleek, basic, fast and responsive date selector instead of Calender date selector or conventional interfaces.

Download

Auto-Date is hosted at google code and code can be downloaded from here. Unzip the files and go through the README file and open index.html

Javascript Autocomplete Date Selector

Javascript Autocomplete Date Selector

Demo

Enter the date in any format. Currently year is in YY, so to enter 2030 you need to type 30 only.

Here is the Demo of the plugin to try out

About Auto-Date

Auto Date v1.0.2 is an amazing JS based auto-complete date selector under MIT-LICENSE which uses the Prototype Framework. Its an alternative to calender interface in browser which sounds annoying when one needs to enter future/past dates.

It validates the date before displaying the possible options. It make sure by prompting which date is popping up in your mind. Say for example one types “01/05” it prompts 05 jan or 01 May. Sounds great!

It also understand certain literals as one usually writes in day to day communication e.g today, yesterday, tomorrow, coming weekend, new year, christmas, last month, saturday etc.

Acceptable Date Formats


  • DD MM YY (seperator can be space ” ” , comma “,” , period “.”, forward slash “/”)


    dd mm yy format

    dd mm yy or mm dd yy format

  • MM DD YY (seperator can be space ” ” , comma “,” , period “.”, forward slash “/”)
  • DD MON YY (MON can be (jan/feb/mar etc), seperator can be space ” ” , comma “,” , period “.”, forward slash “/”)


    Month dd yy format

    Mon dd yy or dd Mon yy format

  • MON DD YY (MON can be (jan/feb/mar etc), seperator can be space ” ” , comma “,” , period “.”, forward slash “/”)
  • New year 1 Jan <present year>
  • Christmas 25 Dec <present year>
  • Monday/Tuesday/Wednesday/Thrusday/Friday/Saturday/Sunday (all are coming ones, instead of present week)
  • Weekend/Week
  • Next Month/ Last Month/ Last week/ last weekend/ last sunday/ last monday etc
  • Today/Tomorrow/Yesterday


    Today Tomorrow Yesterday

    Today Tomorrow Yesterday Format

So just start typing and its fast autocomplete feature will take your heart away. Best of all, its all client side so no burden on your server.

Features


  1. Based on Javascript Prototype Library
  2. Multiple Date Format Support
  3. Support for multiple Date Separator.
  4. ONLY_FUTURE_DATE feature. Just set it to true when its called
  5. Literal Support, just by typing some characters
  6. Auto-Complete, it auto-completes as you start typing and show possible options
  7. Support only from 1970 to 2069

    ONly Future Date Support

    Support for ONLY_FUTURE_DATE

    Multiple Date format Support

    Multiple Date Separator Support

For feedback, suggestion, source code or contribution check out auto-date google code