Skip to content

Instantly share code, notes, and snippets.

@onesup
Last active November 21, 2016 08:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onesup/03892e6947cd16646754aa00b0d40b39 to your computer and use it in GitHub Desktop.
Save onesup/03892e6947cd16646754aa00b0d40b39 to your computer and use it in GitHub Desktop.
T아카데미 RoR 수업 발표자료
puts 'Hello Ruby on Rails World'

발표자료 공유


[fit] 발표자료는 MarkDown 문서 형태입니다.


수업준비

  • 슬랙 가입
  • 깃헙 가입
  • 클라우드9 가입

dffdf.slack.com

이메일 제출 주소 http://bit.ly/ror-class-email


루비 온 레일스

최신버전 5.0 교재는 4.2 버전

[fit] 오늘 내일 수업 수준에서는

[fit] 크게 차이 없습니다.


루비 온 레일스 쓰는 서비스

  • 카카오

프로젝트 초반에 쓴다고 합니다. 카카오스토리도 초기에는 RoR로 만들었다고 합니다.


루비 온 레일스 쓰는 서비스

  • 트위터

여기도 초반에는 RoR 로 만들었다고 합니다. 프로토타이핑 전문?


루비 온 레일스 쓰는 서비스

  • 쿡패드

5576만명 가입·230만개의 요리법… 日인구 절반 즐겨찾는 레시피 사이트

“음식으로 세계인 미소 늘리겠다” 창업주 사노 아키미츠의 철학 실천 창업 20년, 시총 2조4000억원 서비스로

기사전문

^ 카카오가 5.7조


루비 온 레일스 쓰는 서비스


left fit

RoR 창시자

DHH 데이비드 하이네마이어 핸슨 David Heinemeier Hansson http://dareyourself.net/2641


left fit

Ruby 창시자

Matz 마츠모토 유키히로 松本行弘 http://www.bloter.net/archives/184564


left fit

Ruby 창시자

Matz 와 나


클라우드9으로 개발환경 세팅

c9.io


Ruby 기초 문법 실습

https://www.ruby-lang.org/ko/documentation/quickstart/


MVC 구조 설명 및 스캐폴딩으로 Hello world 찍어보기


MVC?

모델과 컨트롤러의 분리


성적표 프로그램

http://bit.ly/2eUxUGC


성적표 개발자의 욕망

일을 쪼개고 싶다. -> 단순 업무는 알바 시키고 싶다.


model

Fat model

^ 랭킹 모델


controller

Thin Controller


view

html.erb


매번 나누는거 귀찮다.

패턴을 적용한 프레임워크

#[fit] 그게 rails


rails project 생성

rails new my_app


convention over configuration

설정보다 관례 http://rubyonrails.org/doctrine/#convention-over-configuration


rails 관례

독특함보다는 표준 gem 도 많이 쓰는 gem 을 더 많이 쓰는 경향 DRY - Don't repeat yourself. 복붙 금지


scaffold 정리

scaffold 가이드

rails scaffold 모델명(resource) 컬럼:type 컬럼:type
rails scaffold User name:string age:integer
  • scaffold 실행 뒤엔 db/migrate 파일을 확인 후
  • rake db:migrate 실행
  • rake 실행 후에는 서버 재시작 해야 함
rails g migration add_telephone_to_users telephone:string

관례 사례

  • 단수와 복수 구분
  • 리소스별로 model view controller 이름 통일
  • 기타등등

https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e


액티브 레코드 Association 소개하기

belongs_to
has_many
has_many through

액티브 레코드 메소드

resource.all
resource.children_resources
resource.children_resources << children_resources
resource.children_resources.destroy_all

액티브 레코드 관계 설정 가이드

http://guides.rubyonrails.org/association_basics.html#has-many-association-reference


모델 생성해서 사용자 입력 데이터를 DB 에 입력하기

rails g scaffold provider name email
rails g scaffold user name email
rails g model order user:references product:references
rails g scaffold products name provider:references price

관리자모드 gem 붙여보기

ActiveAdmin

gem 'activeadmin', '~> 1.0.0.pre4'
gem 'inherited_resources', git: 'https://github.com/activeadmin/inherited_resources.git'

gem 인기순위

www.ruby-toolbox.com


Route 개념 소개

http://guides.rorlab.org/routing.html


rest 개념 소개

CRUD: Create Read Update Delete

CRUD -> Create Get Put Delete

Day 1 final

상품 등록 DB 테이블 만들어보기


이미지 업로드

gem 'carrierwave', '>= 1.0.0.rc', '< 2.0'
gem 'carrierwave-imageoptimizer', git: 'https://github.com/zaiste/carrierwave-imageoptimizer.git'
gem 'mini_magick'

product scaffold

rails migration add_contents_image_to_products contents_image

product model

mount_uploader :contents_image, ContentsImageUploader

uploader input

https://gist.github.com/onesup/03892e6947cd16646754aa00b0d40b39#file-uploader_input-rb


product admin

image_preview = -> {
      if f.object.contents_image.present?
        image_tag(f.object.contents_image.url)
      else
        content_tag(:span, "no thumbnail image yet")
      end
    }

f.input :contents_image, as: :uploader, hint: image_preview.call(), removable: false
row :contents_thumbnail do img src: item.contents_thumbnail, height: 200

ruby lambda

동적인 parameter 를 함수에 전달 할 때 사용 자세한 설명 http://blog.nacyot.com/articles/2015-12-07-ruby-proc-and-lambda/

# A formtastic input which incorporates carrierwave uploader functionality.
#
# Intelligently adds the cache field, displays and links to the current
# value if there is one, adds a class to the wrapper when replacing an
# existing value, allows removing an existing value with the checkbox
# taking into account validation requirements.
#
# There are several options:
#
# * Toggle the replacement field with `replaceable: true/false`.
# * The replace file label is translatable as `replace_label` or using option `replace_label: "value"` (like `label`).
# * Toggle the remove checkbox with `removable: true/false` (`true` overrides `required`).
# * The remove checkbox label is translatable as `remove_label` or using option `remove_label: "value"` (like `label`).
# * Override existing file display and links using `existing_html` and `existing_link_html` (like `wrapper_html`).
#
# Example: `form.input :file, as: "uploader"`
#
# Copyright (c) Samuel Cochran 2012, under the [MIT license](http://www.opensource.org/licenses/mit-license).
class UploaderInput < Formtastic::Inputs::FileInput
def linkable?
options[:linkable] != false
end
def replaceable?
options[:replaceable] != false
end
def removable?
options[:removable] != false and (options[:removable] == true or not required?)
end
def method_present?
if object.respond_to?("#{method}?")
object.send("#{method}?")
else
object.send(method).present?
end
end
def method_changed?
if object.respond_to? "#{method}_changed?"
object.send "#{method}_changed?"
else
false
end
end
def method_was_present?
if not method_changed?
method_present?
else
object.send("#{method}_was").present?
end
end
def wrapper_html_options
super.tap do |options|
options[:class] << " replaceable" if replaceable?
options[:class] << " removable" if removable?
options[:class] << " present" if method_present?
options[:class] << " changed" if method_changed?
options[:class] << " was_present" if method_was_present?
end
end
def cache_html
if method_changed?
builder.hidden_field("#{method}_cache")
end or "".html_safe
end
def file_html
builder.file_field(method, input_html_options)
end
def existing_html_options
expand_html_options(options[:existing_html]) do |opts|
opts[:class] << "existing"
end
end
def existing_link_html_options
expand_html_options(options[:existing_link_html]) do |opts|
opts[:class] << "existing"
end
end
def existing_html
if method_present?
# TODO: Add classes based on mime type for icons, etc.
existing = template.content_tag(:span, object.send(method).file.filename, existing_html_options)
template.link_to_if linkable?, existing, object.send(method).url, existing_link_html_options
end or "".html_safe
end
def replace_label_html
template.content_tag(:label, class: "replace_label") do
template.content_tag(:span, localized_string(method, "Replace #{method.to_s.titleize}", :replace_label))
end
end
def replace_html
if replaceable?
replace_label_html <<
file_html
end or "".html_safe
end
def remove_html
if removable?
template.content_tag(:label, class: "remove_label") do
template.check_box_tag("#{object_name}[remove_#{method}]", "1", false, id: "#{sanitized_object_name}_remove_#{sanitized_method_name}") <<
# XXX: There are probably better ways to do these translations using defaults.
template.content_tag(:span, localized_string(method, "Remove #{method.to_s.titleize}", :remove_label))
end
end or "".html_safe
end
def to_html
input_wrapping do
label_html <<
cache_html <<
if method_was_present?
existing_html <<
replace_html <<
remove_html
else
existing_html <<
file_html
end
end
end
protected
def expand_html_options opts
(opts || {}).dup.tap do |opts|
opts[:class] =
case opts[:class]
when Array
opts[:class].dup
when nil
[]
else
[opts[:class].to_s]
end
opts[:data] =
case opts[:data]
when Hash
opts[:data].dup
when nil
{}
else
{"" => opts[:data].to_s}
end
yield opts if block_given?
opts[:class] = opts[:class].join(' ')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment