Acts_as_nested_set ActiveRecord rendered with mx:Tree in Flex

Posted by Bhushan Ahire | Posted in Rails | Posted on 29-01-2008

0

Gr8 post by Daniel Wanja for Use acts_as_nested_set with Flex.

ActiveRecord: app/models/category.rb

 

app/models/category.rb

class Category < ActiveRecord::Base
  acts_as_nested_set
end

Controller: app/controllers/categories_controller.rb

 

app/controllers/categories_controller.rb

class CategoriesController < ApplicationController
  def index
     Category.result_to_attributes_xml(Category.root.full_set)

  end
end

Flex Application: ActsAsNestedSet.mxml

 

ActsAsNestedSet.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="vertical"
    applicationComplete="categories.send()">
<mx:HTTPService id="categories" url="http://localhost:3000/categories" resultFormat="e4x" />
<mx:Tree dataProvider="{categories.lastResult}"
    labelField="@name"
    width="100%" height="100%" />
</mx:Application>

Result:
20071123_categories.jpg

XML generated by Category.result_to_attributes_xml(Category.root.full_set):

 

XML generated by Category.result_to_attributes_xml(Category.root.full_set)

<node name="Main Category" id="15" description="">

  <node name="Cameras & Photo" id="16" description="">

    <node name="Bags" id="17" description=""/>
    <node name="Accessories" id="18" description=""/>

    <node name="Analog Cameras" id="19" description=""/>
    <node name="Digital Cameras" id="20" description=""/>

  </node>
  <node name="Cell Phones" id="21" description="">

    <node name="Accessories" id="22" description=""/>
    <node name="Phones" id="23" description=""/>

    <node name="Prepaid Cards" id="24" description=""/>
  </node>

  <node name="Dvds" id="25" description="">
    <node name="Blueray" id="26" description=""/>

    <node name="HD DVD" id="27" description=""/>
    <node name="DVD" id="28" description=""/>

  </node>
</node>

I used the http://wiki.rubyonrails.org/rails/pages/BetterNestedSet plugin.

Too cool!

Rails REST meets Rails 2.0

Posted by Bhushan Ahire | Posted in Rails | Posted on 29-01-2008

2

Hey, I got a very good post posted by Jeff on http://www.softiesonrails.com/.
I think this will be helpful to me and all rails developers who uses Rails 2.0 which is most REST oriented

We developed those articles when 1.2 was a mature, stable release, and when it had also become clear that 2.0 would not significantly change what had already been achieved in 1.2.

However, Rails 2.0 did fine-tune the way we develop RESTful applications in Rails, prompting us to add one more article and bring the series up to date.

REST Refresher

Let’s review what we covered in the first five articles:

  1. When deciding what controllers you need, think in terms of resources.
  2. Don’t think twice about what actions your controllers should have. Use the Golden Seven for each resource: index, new, edit, create, show, update, delete.
  3. A resource maps to Rails controller, not necessarily to an underlying model.
  4. Deliver your resources in a way that’s appropriate to the user’s experience. Some users want HTML, some want RSS, some want audio, some have big screens, some have tiny cell phone screens, some want to use your application like a web service and expect XML to be returned.
  5. The client application will indicate their preference with the “Accept” header in the http request. Use respond_to in your controller to automatically map the Accept header to your response.

Once you’ve identified a resource that you want to implement, you just need to implement it RESTfully in Rails.

The Hard Way

I can’t believe I’m saying that anything in Rails is actually hard, but if there is a “hard” way to write RESTful code, this would be it (“by hand” is more precise, I suppose). Here’s the recipe:

1. If your resource needs a supporting model, use script/generate model <resource-name> (or ruby scriptgenerate model on Windows). You can now specify any columns you already know your model needs right on the command line, which will give you a nice head start in your migration file.

Don’t forget to rake db:migrate before you start running your tests (you thought I was going to say “running your app”, didn’t you?)

script/generate model Airport city:string identifier:string

2. Generate a nice empty controller with script/generate controller <resource-name> and fill it with the standard seven actions.

script/generate controller Airports

Using textmate? You can steal our Textmate snippet to quickly write all the boilerplate code for you.

3. Create views only for the actions that need them, typically these are:

  • index.html.erb
  • new.html.erb
  • edit.html.erb
  • update.html.erb
  • show.html.erb

In Rails 2.0, the middle part of the template filename maps to the HTTP mime type (more or less), so you might also have files named index.iphone.erb or show.xml.builder.

Also, be sure to learn the cool new form_for syntax in Rails 2.0 that automatically generates the right target url based on whether you give it a new object (which will target the create action) or one that’s already been saved to the database (which will target the update action).

In fact for a nice overview of all that’s new in Rails 2.0, we recommend the PeepCode Rails 2.0 PDF by Ryan Daigle (disclaimer: PeepCode supports this blog.) Ryan’s blog is also an excellent way to keep up on all the new stuff in Rails.

4. Add a map.resources line to your routing file. There are lots of options here, but the simplest looks like:

map.resources :airports

This will generate a package of handy named routes, map incoming action/verb pairs to the right controller action, and automatically ensure that actions like create, update and delete only respond to POST verbs only.

But you knew all this already – it’s been around since Rails 1.2.

5. Always, always, always try to use named routes whenever you use link_to and any other helper method that expects a hash of url options. The syntax of named paths has changed somewhat in 2.0 to make it easier to construct links for the most typical scenarios. Check the Rails API docs and use the new rake routes task as a cheat sheet whenever you need it.

Help Rails Help You

Ok, now for what’s new in Rails 2.0 that can make this process much easier.

Rails 2.0 has two built-in generators to make your RESTful life easier.

1. Generating A Resource Without Views

If you have a model underpinning your resource, you can get 80% of the way done by using the totally awesome resource generator (again, available since Rails 1.2, but somehow few people know about it). It’s syntax is identical to the model generator, but it will also create a RESTful controller with the Golden Seven actions and add a map.resources line for you.

script/generate resource Airport city:string identifier:string

So what was the other 20%? The views are not generated for you.

2. Generating Everything With The Scaffold Generator

You can inch up to 95% of the way for the simplest situations by using the new scaffold generator.

Ok, time out.

We’ve always said that the scaffold generator was bad. Very bad.

So now we’re recommending it?

Not if you’re using 1.2.x or earlier. In that case, do not use the scaffold generator. If you’re using 1.2, you can use the scaffold_resource generator instead.

But in Rails 2.0, the scaffold generator is no longer evil, it is downright righteous. It will create the model, controller, routes, and view scaffolding that demonstrates how to use the new form_for syntax. Very cool stuff. Again, it uses the model generator syntax, so use the singular form of your resource and specify any columns you already know up front:

script/generate scaffold Airport city:string identifier:string

You’ll end up rewriting the views to truly fit your application, but that’s the whole idea. It’s scaffolding, not the real thing, silly.

If you’ve used the resource generator and now want the scaffolded views as well, you’re in luck: Brian Hogan has released a gem to do just that for you.

(Oh, and I know we had you at “easier.”)

Ok, NOW we’re done

We hope this wraps up our REST series. At least for now.

Deploying two rails application with Apache + mongrel on windows

Posted by Bhushan Ahire | Posted in Rails | Posted on 28-01-2008

1

Install Ruby, Gems and then install Ruby on Rails:



sudo gem install rails --include-dependencies

Now download and install Apache 2.2 using, as the fastest way, the msi package.

Now enable the needed modules (url rewriting, proxy, proxy_balancer e proxy_http) by editing the httpd.conf file (under c:Apache_Software_FoundationApache2.2conf, if you installed Apache in its standard path). You just need to uncomment the following lines (remove the #):



LoadModule rewrite_module modules/mod_rewrite.so
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
LoadModule proxy_http_module modules/mod_proxy_http.so

Install the mongrel and mongrel_service gems:



gem install mongrel (pick last version for win32)
gem install mongrel_service (pick last version for win32)

Now we will create a mongrel cluster of 2 windows services responding at http://127.0.0.1 on ports 3010, 3011 serving a rail application at the path c:wwwrormyapp that will be started from the windows system user. The two windows services will be respectively named mongrel_myapp1 and mongrel_myapp2. Open the command prompt and type:



mongrel_rails service::install -N mongrel_myapp1 -p 3010 -e production -c c:wwwrormyapp
mongrel_rails service::install -N mongrel_myapp2 -p 3011 -e production -c c:wwwrormyapp

Now open the windows services tool, make the 2 new services have an automatic startup type (so they will still be started when you reboot).
Test if your application is now running at the two ports:



http://localhost:3010

http://localhost:3011

If everything is working fine, you are ready to place Apache in front of these 2 mongrel services, to manage the load balancing of you application.

The best way to configure Apache is to create a Virtual Host for your ROR application. First edit your httpd.conf file, and uncomment the following line:



# Virtual hosts

Include conf/extra/httpd-vhosts.conf

Now edit the httpd-vhosts.conf file, like this (keep the slashes in the *nix fashion!):



NameVirtualHost *:80

#Proxy balancer section (create one for each ruby app cluster)
<Proxy balancer://myapp_cluster>
  BalancerMember http://myapp:3010
  BalancerMember http://myapp:3011
</Proxy>

#Virtual host section (create one for each ruby app you need to publish)

<VirtualHost *:80>
  ServerName myapp
  DocumentRoot c:/www/ror/myapp/public/

  <Directory c:/www/ror/myapp/public/ >
      Options Indexes FollowSymLinks MultiViews
      AllowOverride All
      Order allow,deny
      allow from all
  </Directory>

  #log files
  ErrorLog /var/log/apache2/myapp_error.log
  # Possible values include: debug, info, notice, warn, error, crit,
  # alert, emerg.
  LogLevel warn
  CustomLog /var/log/apache2/myapp_access.log combined

  #Rewrite stuff
   RewriteEngine On

  # Check for maintenance file and redirect all requests
  RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
  RewriteCond %{SCRIPT_FILENAME} !maintenance.html
  RewriteRule ^.*$ /system/maintenance.html [L]

  # Rewrite index to check for static
  RewriteRule ^/$ /index.html [QSA]

  # Rewrite to check for Rails cached page
  RewriteRule ^([^.]+)$ $1.html [QSA]

  # Redirect all non-static requests to cluster
  RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
  RewriteRule ^/(.*)$ balancer://myapp_cluster%{REQUEST_URI} [P,QSA,L]

</VirtualHost>

Add your app as a host in hosts.file (in the c:WINNTsystem32driversetc folder):



127.0.0.1 localhost
127.0.0.1 myapp

Restart now Apache from the Windows services panel, and if everything is fine you should have your app served by Apache at the following url:

http://myapp

Add sql session store to rails application

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

Only Mysql, Postgres and Oracle are currently supported (others work, but
you won’t see much performance improvement).

Step 1

If you have generated your sessions table using rake db:sessions:create, go
to Step 2

If you’re using an old version of sql_session_store, run

    script/generate sql_session_store DB

where DB is mysql, postgresql or oracle

Then run

    rake migrate

or

    rake db:migrate

for edge rails.

Step 2

Add the code below after the initializer config section:

    ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.
      update(:database_manager => SqlSessionStore)

Finally, depending on your database type, add

    SqlSessionStore.session_class = MysqlSession

or

    SqlSessionStore.session_class = PostgresqlSession

or

    SqlSessionStore.session_class = OracleSession

after the initializer section in environment.rb

Step 3 (optional)

If you want to use a database separate from your default one to store your
sessions, specify a configuration in your database.yml file (say sessions),
and establish the connection on SqlSession in environment.rb:

   SqlSession.establish_connection :sessions

IMPORTANT NOTES

  1. The class name SQLSessionStore has changed to SqlSessionStore to let Rails
    work its autoload magic.
  2. You will need the binary drivers for Mysql or Postgresql. These have been
    verified to work:

    • ruby-postgres (0.7.1.2005.12.21) with postgreql 8.1
    • ruby-mysql 2.7.1 with Mysql 4.1
    • ruby-mysql 2.7.2 with Mysql 5.0

Add + in URL insteade of space (%20)

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

This is a workaround to get spaces in URL as pluses not %20 like it is in Rails2.

module ActionController::Routing
  class DynamicSegment
    def interpolation_chunk
      "#{CGI.escape(#{local_name}.to_s)}"

    end

    def match_extraction(next_capture)
      default_value = default ? default.inspect : nil

      %[
        value = if (m = match[#{next_capture}])
          CGI.unescape(m)
        else

          #{default_value}
        end
        params[:#{key}] = value if value
      ]
    end

  end
end

Shorcuts for kill and restart rails server

Posted by Bhushan Ahire | Posted in Rails | Posted on 22-01-2008

0

More lovely alias commands… this time to kill/restart Rail’s script/server from any Terminal session or login on your box… (as long as your the same user).

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'