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 🙂

 

 

No to apache/nginx configs. zero-config Rack server for Mac OS X

Are you developing Rails application from a while? I’d be interested to hear how do you run it locally especially on Mac OS X.

Possible options are:

My preferred choice is phusion passenger for Apache or Nginx and writing VirtualHost config everytime I create a new Rails application. Listen to new port and set the virtual host and restart apache or nginx. Boom. Done.

Else it’s good to start Mongrel or webrick instances if Apache/Nginx is down and it’s up in a minute or when Virtual Host port and configs start becoming confusing.

Recently I got to install POW.CX

Pow is a zero-config Rack server for Mac OS X. Have it serving your apps locally in under a minute.

Install it using

$ curl get.pow.cx | sh

To set up a Rack app, just symlink it into:

$ cd ~/.pow $ ln -s /path/to/myapp

 

That’s it! Your app will be up and running at http://myapp.dev/. See the user’s manual for more information.

Also one can use powder which manages POW and makes easy pow more easier .

https://github.com/Rodreegez/powder

It’s simple, straight and offers Convention over Configuration. No more configs or running mongrel instances to start an application.

Vim, TextMate and Gedit, make your editor rich featured

Editors => Idioters

There are hundreds of editors available in the market, both free and paid, depending upon ones need. I mostly work on Ruby or ROR, Web2.0 stuff and I prefer to work fast, efficient and effective way and editor plays a very important role for every developer, so as system (OS) but its a different discussion as of now.

I’ll make my assumptions on the basis you like working either on MacOS X or linux (Ubuntu, fedora or any other flavour) and can dig yourself to get your things working like the way you want to work on your machine. Sorry, I don’t recommend Windows for development and I presume that you like to learn shortcuts and emphasize more upon your keyboard instead of mouse.

I started development during my college days on Vim or GEdit on Linux. Truly speaking VIM seemed flamboyant with its unmatched capabilities. I always wanted to work/handson/try Emacs there after, but still lazy enough to start exploring it.

After college, I started development on Mac OS X and got paid version of TextMate and as said its best for development for Ruby on Rails application. I was pretty happy and used to install some bundles from time to time to make it work the way I want to code fast and effective and started coding with as many shortcuts I can learn and remember. As a rescue I used Vim and always feel overwhelmed about Linux community and such a powerful and fast editor, which can’t be replaced by anything (with same regard for Emacs).

With time I worked more on Vim and TextMate and trying to point some of their key features which I liked and used the most.

Vim (all terminal based and though fast):

  • Searching (/search_string)
  • Search and replace (:%s/search/replace/gi)
  • Macro (record and play on a file of any size), at par feature
  • Practically open file of any size (tried with gigs of sql files)
  • Use of CTags (extremely powerful feature when working on a project)
  • GVIM with more additional feature
  • Split (horizontal and vertical) views (:sp or :vsp <filename>)
  • Automated indentation
  • Color schema makes one feel geeky developer 🙂 especially after watching MatriX
  • Thousands of other feature and plugin and it makes it extremely powerful and fast to work till now

TextMate (a high-hyped editor):

  • Snippets to call your programming structures e.g. def+tab will complete the function block
  • Supports almost all languages and frameworks
  • It can open your whole project (in a side pane, left or right side), I prefer right side. I love this feature
  • Allows you to remove reference certain files or folders from project to apply search upon e.g logs, images etc
  • except common feature, it allows full project search (even regular expression)
  • Star Me and CmdT allows to reach any part of the file and to file in your open project by just typing some literals
  • Auto file indent (Cmd] or SftCmd[ )
  • Cmd/ to auto comment line or lines
  • Most importantly, it won’t annoy you some red or green light here and there or extra fancy stuff and provide more space to code and keep it elegant
  • I like the twilight theme to work upon
  • Takes up very less memory(as compared to most rich featured editors) and its pleasant to work upon it

Textmate

Recently, I moved to Delhi and started working on Linux and to be frank its a hard transition to work without TextMate. Thanks to VIM again, it wasn’t a hard transition. Gedit is good but its like Notepad of windows and reasonably nothing is there. Than I started making it feature rich owing to the fact its always fast to load and can be my textmate on linux. Thanks to hundreds of plugins available and for such a vibrant community around and the research already done by other folks.

So lets talk about different plugins for Gedit to make it work fast, efficient, elegant and more like TextMate

Gedit (conventional and basic editor):

Here are hundreds of plugins available but choosing the right one is important.

How to install additional Gedit plugins

While Gedit ships with a set of default plugins, you can surely add as many as you like. To install a plugin for Gedit, you must first download it to a local folder and then extract the contents to ‘~/.gnome2/gedit/plugins/’ directory. Also look for a package named “gedit-plugins” in your distribution’s package manager, this package contains some additional plugins for gedit. Once you have installed the plugin you want, you need to enable it via Edit -> Preferences and then the Plugins Tab.

  • Snippets -> allows you to insert frequently typed phrases and text by using hotkeys or a shortcode, it supports mostly all the languages
  • Auto Tab  -> detects the indent/space settings in a file and adjusts tabbing accordingly on the fly
  • File Browser Pane -> It open up a whole project in directory structure ( file structure)
  • Right Pane -> For right hand side pane for project viewer
  • Code Comment -> To comment your code (CTL+m)
  • External Tools -> Execute external commands and shell scripts


  • Quick Open -> Its good but not as good as CMDT of textmate
  • Regex Search and replace -> CTL + H for regex search and replace
  • Gemini -> character completion
  • Change Case -> for fast switching case for selected text
  • Class Browser -> List all the methods of class or module, uses Ctags and side pan view
  • Commander -> to provide command line interface
  • Document Statistics -> Analyses the current document and reports the number of words, lines, characters and non-space characters in it.
  • Embedded Terminal and Open terminal here
  • File Search -> Search for text in all files in a directory
  • Session Saver -> Session saver allows you to save you current workspace
  • Snap Open -> A regex open file dialog that resembles that of Textmate
  • Tag List -> Provides a method to easily insert into a document commonly used tags/strings without having to type them
  • Word Completion -> suggestions from all words in all documents in all windows, annoying sometimes

Colors and fonts:

Get all themes from here. But I prefer these two.

  • Rubycious
  • Twilight

So, after go through of important features of all these editors. Its one like and dislike or any editor (other than these three). Vim is always the winner, as it comes with these features and the moment you do code review or sit on someone else computers, it takes no time to work on new machine. Vim is a must for any programmer (If I infer it right, it makes you think above conventional ways). On top of it, while working on a project and other than terminal TextMate (Mac) and Gedit (Linux) is no-doubt a better option.

To comment on Windows based editors GVim, e-text editor with cygwin and notepad ++  seems to be better and fast option.
Happy Coding!

Railscasts crawler (Download all screencasts easily)

I wrote this script, as I felt really annoying to download each screencast everytime I needed them. So I ended up writing script to automatically download all screencasts without hassle i.e crawler.

Its in Ruby of course 🙂 and requires simple Hpricot gem.
If you not having it. Just type this command in your terminal —

$gem install hpricot

–Rest include this script in your /lib folder
–Change the path in the script where you want to download all the screencasts
–Go to your projects development environment (script/console) and run the script by these commands–
video = Railscasts.new #new Railscasts object
video.start #will start downloading all screencasts from Railscasts
Note:
  1. If you stop the script in between manually, it will not download those screencasts that are already in your hard disk.
  2. All logs are maintained in Railsproject/log/railscasts.log.
  3. Handling all exceptions raised

Improvements/Suggestions  are appreciated.

Thanks
And yes script:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
</pre>
<pre># Author : Akshay Gupta</pre>
<pre>#file: railscasts.rb
# First check you have all gems installed. Place the script in /lib folder and run the script.
# I don't have expertize in ruby, please tell how it can be improved.
# change the path accordingly, where you want to save path
# My working env is on MacOS, one need to make some changes if running on Windows
<code>
require 'rubygems'
require 'hpricot'
require 'open-uri'
require 'logger'
$log = Logger.new('log/railscasts.log')
$path = "/Users/akshaygupta/railsvideo/railscasts/"
$stop = false

class Railscasts
attr_accessor :url

def initialize
  @@page = 1
  @@url  = "http://railscasts.com/episodes?page="
  start
end

def url
  @url = @@url+@@page.to_s
end

def start
  url
  build_doc
  screencasts_links
  download_screencasts
  next_page
  if !$stop
    start
  else
    puts "Successfully done :) Enjy all the screencasts"
  end
end

def build_doc
  begin
    $log.info("*********Fetching #{@url}***********")
    @doc = Hpricot(open(@url))
  rescue Exception =&gt; e
    $log.debug("Problem fetching #{e}")
  end
end

def screencasts_links
  begin
    @download_links =
      (@doc/".download/a[1]").collect {|a| (a.search("[@href]").first[:href])}
    $log.info(" All Download links on this page :\n #{@download_links}")
  rescue
    $log.info("Problem in download links")
  end
end

def download_screencasts
  @download_links.each do |mov|
    begin
      file = mov.split('/').last
      res = `cd #{$path}; ls | grep "#{file}"`
      if !res
        $log.info("Now downloading file #{file}")
        result = `cd #{$path}; wget "#{mov}"`
        if result
          $log.info("Successfully Downloaded #{file}")
        end
      else
        $log.info("Already downloaded #{file}")
      end
    rescue Exception =&gt; e
      $log.info("problem downloding file #{e}")
    end
  end
end

  def next_page
    if @@page &lt; 17
      @@page += 1
    else
      $log.info("All screencasts downloaded :-), Mission accomplished!!")
      $stop = true
    end
  end
end</code></pre>
<pre><span style="font-family: monospace;">