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  

end  

end  

 

def self.down  

drop_table :users  

end  

end

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'

ActiveRecord::Base.establish_connection(YAML::load(File.open('database.yml')))

class Users < ActiveRecord::Base

end

&#91;/sourcecode&#93;

And here is the database.yml file

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

adapter: sqlite3

  database: development.sqlite3

  pool: 5

  timeout: 5000

&#91;/sourcecode&#93;

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 )  

   end  

   task :environment do  

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

   ActiveRecord::Base.establish_connection(dbconfig)  

   ActiveRecord::Base.logger = Logger.new(File.open('database.log', 'a'))  

  end 

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


require 'rubygems'

require 'active_record'

require 'users'

Users.create(:name=>"leakhina")

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">
<test>
<created-at type="datetime">2009-03-19T08:47:57Z</created-at>
<id type="integer">1</id>
<name>my lab</name>
<sex>M</sex>
<updated-at type="datetime">2009-03-25T01:59:10Z</updated-at>
</test>
<test>
<created-at type="datetime">2009-03-24T08:15:14Z</created-at>
<id type="integer">2</id>
<name>jack</name>
<sex>M</sex>
<updated-at type="datetime">2009-03-24T08:15:14Z</updated-at>
</test>
</tests>

Code example

First you need to create one class called Test:

require 'rubygems'

require 'activeresource'

class Test < ActiveResource::Base

self.site = "http://localhost:3000"

end
&#91;/sourcecode&#93;

<em>
</em>

<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;”

solr-ruby

Leave a comment

Features

  • 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 http://svn.apache.org/repos/asf/lucene/solr/trunk/client/ruby/solr-ruby
  • 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 = Solr::Connection.new('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
  end

  # delete document by id
  conn.delete(123)

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 = Net::HTTP.new('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

end

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

@y = value

 end 

end

Statements and Control Structures

Leave a comment

1-if


if expression

code

end

2-else

</pre>
if expression
  code
else
  code
end

Older Entries