Wednesday, July 25, 2007

linux tidbit - Finding the working directory of a process

If you are working on multiple Ruby on rails apps, you will have at least 2-3 instances running on your machine at the same time. It is a chore to keep straight the port numbers with project directories (hmm maybe I should write a plugin for this :~))

I was in a similar situation where I couldn't recall why a RoR instance was running on one of the ports.

So I did a ps -auxww to get the process id of the process and then

cp> cd /proc/[process_id]/cwd
cp> pwd
/home/cpatil/....


Pretty cool!
/proc is a virtual filesystem and allows you to peek inside the OS kernel at runtime and find information about the processes running on the machine. Google for it, a one time read is a must for all linux users, young and old.
It is quite funky the way it is set up. For e.g. most files are 0 bytes and you need to do a cat to read it. Stuff like that.

Tuesday, July 24, 2007

Rails: Calling another action

It is interesting how Rails behaves when one action calls another as part of processing a request.

Here is my test:

app/controllers/test_controller.rb
def action1
@foo = "action1"
end

def action2
@foo = "action2"
end

app/view/test/action1.rhtml
<h1>action1.rhtml</h1>
<h2><%= @foo %></h2>

app/view/test/action2.rhtml
<h1>action2.rhtml</h1>
<h2><%= @foo %></h2>

Here is what I observed when I call action2 from action1 like so:

def action1
@foo = "action1"
action2
end

def action2
@foo = "action1"
end

  • If none of the actions have a render explicitly defined, then calling action2 from action1 will simply execute the logic defined in the action2 method. The template that will be rendered will be action1.rhtml
  • If both of the actions have a render explictly defined, then calling action2 from action1 is a multi-render error. It doesn't matter if you use render :template or render :action or just render.
  • If only action2 has an explicit render defined, then
    - action2 method is executed
    - if action2 calls a default template render, then action1.rhtml will be used as the template
    - if action2 calls a specific template, say render :action => 'action2', then action2.rhtml is used.
    Note that it is a multi-render error in this case if action1 also has an explicit render defined in it.