잊지 않겠습니다.

[업어온 글 : 출처 http://kousenit.wordpress.com/2006/0...rvice-clients/

Yesterday I was in a Barnes and Noble bookstore and I started browsing through the Ruby Cookbook by Carlson and Richardson.

Quick aside: I still can’t believe how quickly Barnes and Noble has descended from a decent bookstore into practically garbage, especially as far as software development is concerned. The number of development books is down to a tiny fraction of that a few years ago, certainly no more than 5%. I was so happy when a BN opened in Glastonbury near my (old) house and unfortunately it’s still the closest bookstore to me, but now it’s just depressing. Even leaving aside the drop in selection, as Malcolm Gladwell points out in The Tipping Point, context matters. If nothing else, the managers of the store in Glastonbury could help themselves considerably if they would just oil the stupid door hinges (it’s been literally years since this was done) and clean the bathrooms every once in a while. If there was a Borders anywhere near them I’d never go in that store again.

Bruce Tate in his book Beyond Java points out that Java developers rarely look outside of Java because the field keeps moving so quickly they feel they have to run as fast as they can just to keep up. I really understand that feeling. At the end of December of 2005 I decided I was going to learn Ruby and Rails. I spent the next couple of months really digging into them and made a lot of progress. Ruby is sufficiently different from Java that it’s not at all an easy transition, though, despite what Rubyists say, and I learned just enough to get stuck on a regular basis.

Eventually I had to go back to Java, partly because I understand it and partly because it’s still paying the bills. I really need to become good at Hibernate, Spring, JSF, Tapestry, etc, and they all take time. Consequently, around the middle of March I switched gears and began really digging into Hibernate again, as I’ve mentioned here on several occasions.

Still, the allure of Ruby is strong. I think I may be past the newbie stage, but I’m hardly any good at it yet. On a scale from 1 to 10, I’d give myself about a 4, and that mostly based on reading rather than experience. I did read the pickaxe book (Programming Ruby by Dave Thomas) and R4R (Ruby for Rails by David Black) as well as the RoR books Agile Web Development with Rails (Dave Thomas again, among others) and a couple of the O’Reilly Rough Cuts. In other words, I’ve read the background material but haven’t yet gone through more than a couple of the Ten Canonical Errors in each technology.

Anyway, I mentioned here that about a week ago I decided to write a quick web service client for my Rensselaer students. I used the Amazon web service, connected with the URL class in Java, and parsed the resulting DOM tree (not fun). So yesterday I was browsing through the Ruby Cookbook, as I said, and found this code from Recipe 16.1:

require 'amazon/search'

$AWS_KEY = 'Your AWS key goes here' # See below.
def price_books(keyword)
  req = Amazon::Search::Request.new($AWS_KEY)
  req.keyword_search(keyword, 'books', Amazon::Search::LIGHT) do |product|
    newp = product.our_price || 'Not available'
    usedp = product.used_price || 'not available'
    puts "#{product.product_name}: #{newp} new, #{usedp} used."
  end
end

price_books(’ruby cookbook’)Wow. It depends on a third party library, but I found that easy to download and install. I tested it out using my RadRails editor and it worked like a charm, with all the product information already converted into a Product class.

Even more amazing is this little snippet from Recipe 16.7, Using a WSDL File to Make SOAP Calls Easier:

require 'soap/wsdlDriver'
wsdl = 'http://services.xmethods.net/soap/urn:xmethods-delayed-quotes.wsdl'
driver = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver

puts "Stock price: %.2f" % driver.getQuote('TR')

Holy cow. That’s three lines, really, and you can invoke a web service without even having to download the WSDL file. I wrapped it in a class and tried various web services at Xmethods.net and it worked without a problem. Not only that, but the “soap/wsdlDriver” library is built into Ruby 1.8.4.

I don’t even need a comment here. I simply have to find time to build up some experience with Ruby, and then go back to Rails, definitely by the time the next version of the AWDR book comes out. I purchase the “beta book” version from the Pragmatic Programmers already, but I think the hard copy becomes available in the Fall.

Posted by Y2K
,

Database에서의 각각의 객체간의 관계의 정의

belongs_to

1:N 관계에서 1을 나타낸다.

has_many

1:N 관계에서 N을 나타낸다.

class Slide < ActiveRecord::Base
  belongs_to :slideshow
  belongs_to :photo
end
class Photo < ActiveRecord::Base
  has_many :slides
  validates_presence_of :filename
end

  

class Slideshow < ActiveRecord::Base
  has_many :slides
end

  

has_one

1:1 관계를 나타낸다.

belogs_to, has_one을 이용 pair로 구성

  • belogs_to : 기본 Key가 있는 Table
  • has_one : 외래키가 있는 Table

  

Posted by Y2K
,

ActiveRecord - Rails application과 Database 간의 연동을 담당.

   

ActiveRecord
  • Record 객체를 통해서 Database Table을 조작
  • 각각의 Record는 Database의 각각의 row와 대응 : create, read, update, delete 가능

  

 차이점  장점

 Rails는 Database table에 정의된 Column을 기반으로 하여 속성을 자동으로 추가한다.

Rails는 내부 언어로 관계 관리와 검증을 한다.

Rails 작명 규약은 DB의 특수한 필드를 자동으로 찾아낸다.

개발자는 속성을 지정할 때, DB만을 추가하면 된다. 

Rails 개발자는 관계와 모델 기반의 검증을 코드 생성없이 프레임워크 자체적으로 할 수 있도록 선언할 수 있다.

Rails 개발자는 주키나 후보키를 따로 설정할 필요가 없다.

   

OR Mappting
  • Datatabe Table과 object를 각각 생성.
  • Java Framework 에서 주로 사용되는 방법
  • 여러 종류의 Database Schema 지원
  • setting 파일의 복잡
  • 코드의 중복 가능

   

ActiveRecord on Rails
  • Setting대신 규약 : 규약에 의하여 Database Schema를 가져오는 것이 가능하다.
  • MetaProgramming
  • Mapping 언어 : Ruby를 이용하여 또 다른 언어를 만든다.

  

Rails 에서의 Active Record Model object 생성
  1. config/databasel.yml 수정
  2. Model 객체의 생성 (ruby script/generate model Photo)
  3. migration의 수정 - DB의 column의 설정(ruby에서 db의 table의 생성 및 수정 가능)
  4. migration의 실행 (rake db:migrate)

class CreatePhotos < ActiveRecord::Migration
  def self.up #DB Table의 생성
    create_table :photos do |photo|
      photo.column "filename", :string
    end
  end

  def self.down #DB Table의 삭제
    drop_table :photos
  end
end

   

Active Record Class
Class와 Table 이름
  • Active Record Class의 영문 복수형을 Database table 이름으로 간주하여 Table을 찾고, 만들어준다.
식별자
  • "id" 라는 column을 자동으로 생성하고 primary key로 만들어준다.
  • "id"는 정수형이며, auto-increase 속성을 갖는다.
외래키
  • "<classname>_id" 형태로 지어지게 된다.
표기 방법
  • Active Record class는 모두 Camel casing에 따라 지어지게 된다.
  • 공백은 모두 '_'로 채워지게 된다.

  

Rails Console

Database와 Model간에 유기적인 결합을 만들어준다.

  • DB에 연결
  • app/model에 있는 Active Record Class들을 불러온다.
  • Database와 Model간에 DB 작업을 포함하여 유기적인 작업을 할 수 있도록 하여준다.

photo = Photo.new
photo.filename = 'dog.jpg'
photo.save


photo = Photo.find_by_filename('dog.jpg')

  

Finder
  • find_by_sql : 직접 SQL Query 문을 입력하여 검색
  • find_all : 모든 항목 얻어오기
  • find_by_<column>(and...) : 항목으로 얻어오기

  

Transaction

: Record에 대한 Transaction 구현 역시 완벽.

def transfer(from, to, ammount)
  Account.transaction do
    from.debit(amount)
    to.creadit(amount)
  end
end
Posted by Y2K
,