ActiveRecord By Example

Leave a comment

Now I would like to show about how to create a simple ActiveRecord example of User.

First thing, we assume that we have one entity called User as below :

We put the file under “activerecord/db/migrate/001_create_user.rb”

class CreateUsers < ActiveRecord::Migration  

def self.up  

 create_table :users do |t|  

t.column :name, :string, :null => false  




def self.down  

drop_table :users  



And then we create users class that inherit from ActiveRecord::Base that call database connection from database.yml that store information of database connection

require 'rubygems'

require 'active_record'


class Users < ActiveRecord::Base



And here is the database.yml file

&#91;sourcecode lang='xml'&#93;

adapter: sqlite3

  database: development.sqlite3

  pool: 5

  timeout: 5000


After that we create rake file to migate data to database

&#91;sourcecode lang='ruby'&#93;

require 'rubygems'

require 'active_record'

require 'yaml'

require 'rake'      

   task :default => :migrate        

   desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"  

   task :migrate => :environment do  

   ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil )  


   task :environment do  

   dbconfig = YAML::load('database.yml')) 


   ActiveRecord::Base.logger ='database.log', 'a'))  


In the end we create one more file called runner.rb to run the example

require 'rubygems'

require 'active_record'

require 'users'



Active Resource Example in Ruby

Leave a comment

Assume that you have rest url “http://localhost:3000&#8221; that return as xml as below:

Output from http://localhost:300

<tests type="array">
<created-at type="datetime">2009-03-19T08:47:57Z</created-at>
<id type="integer">1</id>
<name>my lab</name>
<updated-at type="datetime">2009-03-25T01:59:10Z</updated-at>
<created-at type="datetime">2009-03-24T08:15:14Z</created-at>
<id type="integer">2</id>
<updated-at type="datetime">2009-03-24T08:15:14Z</updated-at>

Code example

First you need to create one class called Test:

require 'rubygems'

require 'activeresource'

class Test < ActiveResource::Base = "http://localhost:3000"



<strong>And now we call the created Test class</strong>:

T = Test.find(1)

Note: Class Name and XML tag name must be the same without case sensitive.

How to convert special html characters in Ruby

Leave a comment

CGI::escapeHTML('Usage: foo "bar" <baz>')
  1. => “Usage: foo &quot;bar&quot; &lt;baz&gt;”


Leave a comment


  • Solr HTTP communication handling

Our working task list: solr-ruby/ToDo

Trying out solr-ruby

  • Install the solr-ruby gem gem install solr-ruby or check out solr-ruby from Subversion svn co
  • Launch Solr: java -Dsolr.solr.home=<path to solr-ruby's solr directory> -jar start.jar
    • You must have Solr 1.2 already installed. This example assumes you are using the schema found under <path to solr-ruby/solr/conf directory> .
  • (in a separate shell) Launch irb (be sure to include the solr-ruby lib directory in your load path):
  require 'solr'

  # connect to the solr instance
  conn ='http://localhost:8983/solr', :autocommit => : on)

  # add a document to the index
  conn.add(:id => 123, :title_text => 'Lucene in Action')

  # update the document
  conn.update(:id => 123, :title_text => 'Solr in Action')

  # print out the first hit in a query for 'action'
  response = conn.query('action')
  print response.hits[0]

  # iterate through all the hits for 'action'
  conn.query('action') do |hit|
    puts hit.inspect

  # delete document by id

Using Solr’s Ruby output

Leave a comment

Solr has an optional Ruby response format that extends its JSON output in the following ways to allow the response to be safely eval’d by Ruby’s interpreter:

  • Ruby’s single quoted strings are used to prevent possible string exploits
    • \ and ‘ are the only two characters escaped…
    • unicode escapes not used… data is written as raw UTF-8
  • nil used for null
  • => used as the key/value separator in maps

Here is a simple example of how one may query Solr using the Ruby response format:

require 'net/http'

h ='localhost', 8983)
hresp, data = h.get('/solr/select?q=iPod&amp;wt=ruby', nil)
rsp = eval(data)

puts 'number of matches = ' + rsp['response']['numFound'].to_s
#print out the name field for each returned document
rsp['response']['docs'].each { |doc| puts 'name field = ' + doc['name'] }

Getter And Setter

Leave a comment

class MutablePoint

def initialize(x,y); @x, @y = x, y; end

def x; @x; end # The getter method for @x

def y; @y; end # The getter method for @y

def x=(value) # The setter method for @x

@x = value


def y=(value) # The setter method for @y

@y = value



Statements and Control Structures

Leave a comment


if expression




if expression

Older Entries