2012년 5월 19일 토요일

Rails에서 요청이 처리되는 과정.

출처는 ruby.railstutorial.org의 Chapter2

mvc_detailed

1. 브라우저가 /users URI에 대한 요청을 보낸다.
2. Rails는 /users URI를 보고 Rails router(config/routes.rb)를 통해 User Controller의 index action으로 보낸다.
3. index action의 내용은 User Model에게 모든 user의 데이터를 달라고 하는 내용이다.
4. User model은 데이터베이스로 부터 모든 user의 데이터를 꺼낸다.
5. User model이 꺼낸 데이터를 controller에게 준다.
6. controller는 이 데이터를 @users 변수에 저장한 뒤, index view에게 보낸다.
7. view는 erb파일을 통해 페이지를 html로 렌더링한다.
8. controller는 html을 다시 브라우저에게 전송한다. 물론 서버 데몬에게 건내주는 거겠지.

그럼 잠깐 config/routes.rb 파일을 보자면
DemoApp::Application.routes.draw do
  resources :users
  .
  .
  .
end

여기서 루비 문법에 대한 얘기는 문법을 아니까 미루도록 하고, resources :users에 대해 알아보도록 하자. 이것을 알려면 어디로?

내 생각에 rails tutorial을 가장 효율적으로 보는 방법은 rails guide와 같이 보는 것 같다. rails tutorial은 내용이 개발과정에 따라 선형적으로 구성되어 있어 익히기에는 좋지만, rails 자체를 파악하는 데는 목마름이 있다. 과정에 필요한 부분만 쓰여있기 때문이다. 따라서 이런 목마름을 해결하기 위해 rails guide를 참조하는 것이 좋겠다.

Emacs - CEDET이란?

CEDET이란?

CEDET is a Collection of Emacs Development Environment Tools written with the end goal of creating an advanced development environment in Emacs. CEDET is hosted at Source Forge and is Free Software. You can view CEDET's CVS archive, project summary, and mailing lists at the CEDET Project page.

Why is CEDET needed?

Emacs already is a great environment for writing software, but there are additional areas that need improvement. Many new ideas for integrated environments have been developed in newer products, such as Microsoft's Visual environment, JBuilder, or Eclipse. CEDET is a project which implements several advanced features developers have come to expect from an Editor.

결론은 Emacs의 기능을 Eclipse나 비쥬얼 스튜디오 같은 개발툴의 경지까지 끌어올리겠다는 의미.

그럼 CEDET의 특징은?


Projects
The CEDET Project management system provides a few simple keystrokes for organizing your files, building Makefiles or Automake files, and compiling your sources.
If you don't want CEDET to manage your Makefiles, CEDET will still be able to identify some types of projects based on pre-existing build configurations, such as the Emacs sources, the Linux kernel, or any project built using Automake.
The entire CEDET Makefile tree was built with CEDET's project management system, so when you download and build the distribution package, you will be using aCEDET project.
The image to the right shows a part of the Project management menu.

요약 : 비주얼 스튜디오의 프로젝트 처럼 전체를 알아서 make해주는 기능이 있다.

Smart Completion

Write code with smart code completion, sometimes known as "Intellisense". The CEDET infrastructure for parsing and tagging files, and analyzing source code is one of the most accurate completion tools for C++ anywhere. It will correctly handle inheritance scoping rules, templates, smart-pointers, and automatically filters based on what the value will be assigned into.
Code completion is not restricted to just C or C++. The completion engine is generic and works for any language that has a robust tagging parser written for CEDET, and a thin adaptation layer for the language. See the language support page to see if your language is supported.
The image to the right shows smart completion configured to use a popup menu in a CEDET unit test source file going through a templated smart pointer.

요약 : 자동완성이 된다아~! ㅋ 이건 원래 이맥스도 되지만, 스마트한 건 내가 작성한 것들도 뜬다는것~

Smart Help/Jump

Smart help shows the prototype of the variable or method under point. As with the smart completion, it will correctly identify the method under point, deriving it's correct prototype by dereferencing the datatypes through templates and smart pointers.
The smart jump feature is similar to the classic Emacs TAGS feature, except it always goes to the correct location. Using TAGS on a method name makes you scan through all the possible methods with the same name to find the one you want. Using the CEDET smart jump feature takes you to the right definition the first time.

요약 : 이맥스 TAGS보다 정확하게 그 위치로 이동할 수 있다.

Symbol References

Analyze where symbols are referenced in your code base. The Symbol References tool in CEDET can use external tools such as GNU Global, ID Utils, CScope, or even find/grep to locate usages of your symbols. Every location is analyzed and displayed hierarchically showing you the file and function the reference occurs in, instead of a flat list of locations.
The image to the right shows integration with GNU Global running in the GNU Global source code.

요약 : 심볼 관리가 가능해진다. 디버깅이 더 쉬워지겠죠?

Code Generation

Generate code with a powerful language-independent template system. The template system in CEDET is a framework designed for code-generating application developers. Even so, the base system and templates can also be used to insert small repetitive code blocks. The template language is straight-forward, and flexible. Because it uses the same code analytics as the Smart completion, it often can correctly guess a wide range of values to be used in your templates, saving you typing.
Some pre-existing tools that use CEDET's code generation system will write texinfo documentation for you, create doxygen style comments fully filled out from the local context, or insert get/set methods for variables in a class.
The image to the right shows a simple class declaration inserted into an empty buffer.

요약 : 코드를 템플릿에 맞게 자동생성 해준다. HTML5 같은 경우 유용할듯.

UML Diagrams

Create UML diagrams either by hand, or automatically generate simple 3-tier class diagrams from your sources. The diagrams are linked to your source-code, so you can browse quickly through you code from the convenience of UML.
The image to the right shows CEDET's UML tool's source code, called 'COGRE', diagramming and browsing itself. Optional unicode character support is enabled for the special characters.

요약 : 내가 작성한 소스에 맞게 UML을 그려준다. 대박인데? ㅋ

Advanced Code Browsing

With the CEDET parsing backend, advanced code browsing tools like ECB can be used. ECB, or the Emacs Code Browser provides an advanced set of UI windows docked to your Emacs frame. The extra windows provide a wide range of features, including:
  • A list of functions, classes, and methods in the current file
  • A code analyzer/completions list
  • A current definition display
  • A directory tree,
  • A list of source files in the current directory,
  • A history of recently visited files,
  • and many others
The ECB image on the right shows a sample of ECB (in full size). ECB is NOT a part of CEDET, and must be downloaded and installed seperately.


요약 : ECB를 깔면 디렉토리 관리가 Visual하게 가능해진다. dired를 안써도 되는건 물론이고, 클래스와 메소드도 깔끔하게~! ㅋ

2012년 5월 18일 금요일

Rails의 커맨드에 대해 알아보자.

기본적인 레일즈의 기능이나 작동 방식에 대해 학습했다면, 이제 배운 것에 대해 조금 더 깊게 들어가고, 그들의 구조를 머릿속에 짜보자. 그에 앞서 먼저 필요한 것이 Rails의 각종 커맨드에 대해 알아보는 것이다. 먼저 가장 기본적인 명령어에 대해 알아보자.

1. rails New 이름
잘 알다시피 처음 Rails Application을 만들 때 사용하는 커맨드이다. 이름에 자신이 원하는 Application의 이름을 넣어주면 그 이름으로 새로운 디렉토리가 생성이 되고 그 밑에 Rails Application을 운영하는데 필요한 모든 파일이 생성된다. 이 때 옵션을 지정하여 생성될 파일들의 초기 세팅을 맞추어줄 수 있는데, 그 옵션들은 다음과 같다.


Usage:
  rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]              # Path to the Ruby binary of your choice
                                 # Default: /home/koreport/.rbenv/versions/1.9.3-p194/bin/ruby
  -b, [--builder=BUILDER]        # Path to a application builder (can be a filesystem path or URL)
  -m, [--template=TEMPLATE]      # Path to an application template (can be a filesystem path or URL)
      [--skip-gemfile]           # Don't create a Gemfile
      [--skip-bundle]            # Don't run bundle install
  -G, [--skip-git]               # Skip Git ignores and keeps
  -O, [--skip-active-record]     # Skip Active Record files
  -S, [--skip-sprockets]         # Skip Sprockets files
  -d, [--database=DATABASE]      # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                 # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]  # Preconfigure for selected JavaScript library
                                 # Default: jquery
  -J, [--skip-javascript]        # Skip JavaScript files
      [--dev]                    # Setup the application with Gemfile pointing to your Rails checkout
      [--edge]                   # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit]         # Skip Test::Unit files
      [--old-style-hash]         # Force using old style hash (:foo => 'bar') on Ruby >= 1.9

Runtime options:
  -f, [--force]    # Overwrite files that already exist
  -p, [--pretend]  # Run but do not make any changes
  -q, [--quiet]    # Supress status output
  -s, [--skip]     # Skip files that already exist

Rails options:
  -h, [--help]     # Show this help message and quit
  -v, [--version]  # Show Rails version number and quit


2. rails server server_application_name
rails server 커맨드는 WEBrick이라고 불리우는 루비에 같이 탑재된 작은 웹서버를 작동시킨다. 웹브라우저로 자신이 만든 Rails Application을 보고 싶을 때 언제든지 작동시키면 된다. server 대신 s로 써도 된다. server_application_name이 주어지지 않으면 default 값으로 WEBrick이 작동되지만, 나중에 gem으로 mongrel이나 unicorn을 설치했다면 rails server mongrel 이런 식으로 다른 서버 애플리케이션을 실행할 수 있다.
-p 옵션으로 포트를 설정할 수 있고, -e 옵션으로 실행할 rails enviroment를 선택할 수 있다.
rails server -e production -p 4000 이런 식으로.


Usage: rails server [mongrel, thin, etc] [options]
    -p, --port=port                  Runs Rails on the specified port.
                                     Default: 3000
    -b, --binding=ip                 Binds Rails to the specified ip.
                                     Default: 0.0.0.0
    -c, --config=file                Use custom rackup configuration file
    -d, --daemon                     Make server run as a Daemon.
    -u, --debugger                   Enable ruby-debugging for the server.
    -e, --environment=name           Specifies the environment to run this server under (test/development/production).
                                     Default: development
    -P, --pid=pid                    Specifies the PID file.
                                     Default: tmp/pids/server.pid

    -h, --help                       Show this help message.


3. rails generate GENERATOR [args] [options].
rails generate 커맨드는 rails application에서 필요한 요소를 추가적으로 만들 때 실행시키는 커맨드이다. 즉 controller나 view를 만들 때 일일이 자신이 파일을 만들어 넣기 보다는, 이 커맨드를 통해 생성을 하면 정확한 위치에 정해진 이름으로 해당하는 요소의 템플릿을 만들어주기 때문에 매우 편리하다.


Usage: rails generate GENERATOR [args] [options]

General options:
  -h, [--help]     # Print generator's options and usage
  -p, [--pretend]  # Run but do not make any changes
  -f, [--force]    # Overwrite files that already exist
  -s, [--skip]     # Skip files that already exist
  -q, [--quiet]    # Suppress status output

Please choose a generator below.

Rails:
  assets
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  resource
  scaffold
  scaffold_controller
  session_migration
  task

Coffee:
  coffee:assets

Jquery:
  jquery:install

Js:
  js:assets

4.

2012년 5월 15일 화요일

OpenGL 함수 설명.

Display List 만들기
먼저 glGenList(만들어질 list 갯수)로 메모리에 list를 만들 공간을 확보한다. glGenList는 확보된 메모리 공간의 포인터를 리턴한다. 다음 glNewList(확보된 메모리공간 포인터, 옵션)으로 새로운 리스트를 입력한다. glNewList와 glEndList사이의 코드가 새로운 리스트로 들어가는 코드이다. 여기서 glNewList의 옵션을 GL_COMPILE로 하면 코드를 미리 컴파일해놔 속도를 빠르게 하는 효과를 가져올 수 있다. 이렇게 만들어진 리스트는 필요할 때 glCallList(메모리공간 포인터)로 불러와 사용할 수 있다. glCallList는 마치 함수 자리에 미리 입력해놓은 코드가 들어가는 것처럼 작동한다. 리스트를 이동할 때는 보통 포인터를 사용할 때 처럼 정수 연산으로 이동하면 된다. 예를 들어 2번째 리스트로 이동하고 싶다면 메모리공간포인터 + 1을 해주면 이 값은 2번째 리스트의 주소값이 되고, 이 값을 glCallList하면 2번째 저장해논 리스트를 사용할 수 있다.

glMatrixMode에 대하여
glMatrixMode는 openGL의 프로그래밍 중에 자신이 어떤 matrix를 사용할 것인지 지정할 때 사용된다. 즉 openGL이 화면에 결과를 뿌릴 때 오브젝트가 pipeline(일련의 연산과정)을 통해 화면에 뿌려지게 되는데, 이 때 pipeline에 쓰이는 matrix를 바꾸고 싶을 때 사용하는 것이 glMatrixMode이다. 예를 들자면 내가 pipeline에서 화면에 카메라가 보이는 부분, 즉 perspective를 바꾸고 싶다면, glMatrixMode로 GL_PROJECTION을 선택한다음 적절한 값을 넣어주면 그 다음 렌더링 시에는 오브젝트가 pipeline을 지나가면서 내가 설정한 값을 적용받아 렌더링이 되게 된다. mode에는 GL_PROJECTION, GL_MODELVIEW, GL_PROJECTION, GL_COLOR, GL_TEXTURE 네 가지가 있다. 처음에 glMatrixMode(원하는 모드)로 모드를 선택하고, glLoadIdentity()로 해당 모드의 Matrix를 초기화할 수 있다(즉 Matrix를 단위행렬로 만드는 것이다).

변환행렬에 대하여
각 모드에서 처음에 glLoadIdentity()로 매트릭스를 초기화하면 단위행렬이 매트릭스에 저장되게 된다. 이 단위행렬을 전역좌표계라고 보자. 즉 모든 오브젝트들은 이 좌표계 안에서 자기 나름대로의 좌표계를 갖게 된다. 그리고 이동과 확대, 회전등의 매트릭스 변환 행렬은 실제로 오브젝트를 옮긴다기 보다는 좌표계를 옮긴다고 보는게 맞다. 전역 좌표계에서 각종 변환행렬을 적용해 지역좌표계를 만들고, 그 좌표계를 기준으로 자신이 원하는 오브젝트를 그리는 것이다. 변환행렬을 만드는 함수는 여러가지가 있는데, 대표적인 건 다음 3가지이다.
glTraslatef(이동 위치 좌표값) : 이동행렬
glScalef(각 좌표마다 확대 값) : 확대행렬
glRotatef(회전하고자 하는 각도, 기준이 되는 좌표값) : 회전행렬
회전행렬은 기준이 되는 좌표값과 그 전역좌표계의 원점을 이은 벡터를 축으로 하여 회전한다.
좌표계 연산을 하다보면 하나의 좌표계를 기준으로 다른 지역좌표계를 여러 개를 만들 때가 많다. openGL의 절차적인 과정 상 코딩할 때 수정하고 있는 좌표계는 단 하나이므로, 기준이 되는 좌표계나 다른 용도의 좌표계 등 나중에 쓸 것은 미리 저장을 해놔야한다. 이 때 사용하는 함수가 glPushMatrix와 glPopMatrix이다. 이 두 함수를 통해 스택에 좌표계를 저장해놓고, 나중에 필요할 때 갖다 쓰는 것이다.
그리고 openGL에서 제공하는 함수를 이용하는게 아니라 자신이 계산해놓은 임의의 행렬을 변환행렬에 적용시키고 싶을 때는 glMultMatrix을 이용해 자신만의 4X4행렬을 적용시킬 수 있다. 그리고 현재 적용되어 있는 행렬을 얻고 싶을 때는 glGetDoublev(얻고싶은 행렬의 모드, 행렬이 저장될 공간) 함수를 사용하면 된다.

2012년 4월 29일 일요일

Rails를 위한 Ubuntu 초기 세팅!

먼저 우분투의 apt-get을 업데이트하고, 그 다음에 필요한 패키지를 설치하자.

vagrant@lucid32:/vagrant$ sudo apt-get update

vagrant@lucid32:/vagrant$ sudo apt-get install build-essential zlib1g-dev git-core sqlite3 libsqlite3-dev curl

build-essential
Informational list of build-essential packages. If you do not plan to build Debian packages, you don't need this package. Moreover this package is not required for building Debian packages. This package contains an informational list of packages which are considered essential for building Debian packages. This package also depends on the packages on that list, to make it easy to have the build-essential packages installed. If you have this package installed, you only need to install whatever a package specifies as its build-time dependencies to build the package. Conversely, if you are determining what your package needs to build-depend on, you can always leave out the packages this package depends on. This package is NOT the definition of what packages are build-essential; the real definition is in the Debian Policy Manual. This package contains merely an informational list, which is all most people need. However, if this package and the manual disagree, the manual is correct.
패키지를 빌드할 때 쓰인다. 한국말로 풀어쓰자면 종속관계 패키지인데, make할 때 필수이다. 뭐 apt-get만 하면 필요 없지만... 예전에 kernel compile 할 때 이거 안깔아서 애먹었던 기억이 있다. 근데 왜 기본으로 설치가 안되있는거지;; 라이센스 문제인가


zlib1g-dev
zlib is a library implementing the deflate compression method found in gzip and PKZIP. This package includes the development support files.
정의는 저렇지만 ssh-dev에서 쓰기 때문에 의존성 땜시 필요하다.

git-core
git할 때 필수 툴.

sqlite3, libsqlite3-dev
말할 필요 없것제.

curl
Client URL Library Functions의 약자이다. 그러니까 URL 문법으로 클라이언트 측에서 Library를 작동시킬 수 있게 만드는... 툴이지만 대부분 URL을 이용해 library 받아올 때 쓰이는듯;;

HOME 에 가서, rbenv 인스톨

vagrant@lucid32:~$ git clone git://github.com/sstephenson/rbenv.git .rbenv

@@rbenv말고 기능이 확장된 ruby-build? 알아보고 업데이트.

그리고  .bash_profile 의 PATH 에 ~/.rbenv/bin 을 추가.

export PATH="$HOME/.rbenv/bin:$PATH"

미리 PATH 에 NEWDIR 가 있는지 확인하면 PATH 가 깨끗해진다.

eval "$(rbenv init -)" 도 .bash_profile 에 추가.

vagrant@lucid32:~$ source .bashrc

bash_profile는 login, bashrc는 non-login 때 쓰이는 shell script. 하지만 우분투는 bashrc를 쓴다! 로그인 했는데 왜일까;;

이제 루비 설치

vagrant@lucid32:~$ git clone git://github.com/sstephenson/ruby-build.git
vagrant@lucid32:~$ cd ruby-build
vagrant@lucid32:~/ruby-build$ sudo ./install.sh
vagrant@lucid32:~/ruby-build$ rbenv install 1.9.2-p290
vagrant@lucid32:~/ruby-build$ rbenv rehash
vagrant@lucid32:~/ruby-build$ rbenv global 1.9.2-p290
vagrant@lucid32:~/ruby-build$ ruby -v
vagrant@lucid32:~/ruby-build$ cd /vagrant

이제 번들러를 인스톨해주고,
vagrant@lucid32:/vagrant$ gem install bundler
vagrant@lucid32:/vagrant$ rbenv rehash

이제 gem 을 인스톨하고,
vagrant@lucid32:/vagrant$ bundle

V8 JavaScript 엔진이 탑재가 안되어 있는 관계로.

Gemfile 에 therubyracer 를 넣고 다시 bundle
홈