1000 - BB10

bracechumpInternet και Εφαρμογές Web

5 Φεβ 2013 (πριν από 4 χρόνια και 6 μήνες)

718 εμφανίσεις

Ruby on Rails




Web development that doesn't hurt


Tko sam ja?

Branimir Šloser
-

web developer


dimedia, web.burza


emusoft.hr


Tko ste vi?




www.twitter.com/sloser

www.twitter.com/emusoft

Uvod

Dogovor oko satnice


1.sat

Pozdrav, uvod, ponavljanje


2.sat

M
VC


Model
-

ActiveRecord


3 i 4 sat

M
VC

-

Controller, View, Routing, Helpers


ActionController, ActionView, Helpers




PAUZA




5


8.sat

Praktičan rad


9. sat

Testiranje, deploy


Ruby
-

osnove


Ruby is a dynamic (runtime), reflective (metaprogramming),
general purpose object
-
oriented programming language that
combines syntax inspired by Perl with Smalltalk
-
like features.
Ruby originated in Japan during the mid
-
1990s and was
initially developed and designed by Yukihiro "Matz"
Matsumoto. It is based on Perl, Smalltalk, Eiffel, Ada, and
Lisp.



Ruby
-

osnove

Povijest


24.2. 1993 by Yukihiro “Matz” Matsumoto


Matsumoto has stated, "I wanted a scripting
language that was more powerful than Perl,
and more object
-
oriented than Python. That's
why I decided to design my own language".



Ruby 1.0 December 25, 1996


RoR July 2004



Ruby
-

osnove

Philosophy

Often people, especially computer engineers,
focus on the machines. They think, "By doing
this, the machine will run faster. By doing this,
the machine will run more effectively. By doing
this, the machine will something something
something." They are focusing on machines. But
in fact we need to focus on humans, on how
humans care about doing programming or
operating the application of the machines. We
are the masters. They are the slaves.

Matz


Ruby
-

osnove

http://tryruby.sophrinix.com/


Strings, numbers, symbols,
scopes


Time


Arrays, hash


Methods


Class



Rails
-

osnove

Povijest:


Ruby on Rails was extracted by
David Heinemeier Hansson
(DHH) from his work on
Basecamp, a project
management tool by 37signals
(now a web application
company).[2] Heinemeier
Hansson first released Rails as
open source in July 2004, but did
not share commit rights to the
project until February 2005.



Rails
-

osnove

Ruby On Rails (RoR) je open
-
source web framework koji je
optimiziran do maksimuma da bi
programerima olakšao pisanje i
razvoj web aplikacija. Pisan je u
programskom jeziku Ruby.


Služi za razvoj database backend
web aplikacija i site
-
ova, a
temelji se na Model
-
View
-
Control
principu.



Rails
-

osnove

"Convention over Configuration"
means a developer only needs to
specify unconventional aspects of
the application. For example, if
there is a class Sale in the model,
the corresponding table in the
database is called sales by
default. It is only if one deviates
from this convention, such as
calling the table "products sold",
that the developer needs to write
code regarding these names.
Generally, this leads to less code
and less repetition.



Rails
-

osnove

"Don't repeat yourself" means that information is
located in a single, unambiguous place. For
example, using the ActiveRecord module of Rails,
the developer does not need to specify database
column names in class definitions. Instead, Ruby on
Rails can retrieve this information from the
database based on the class name.

Rails
-

osnove

MVC Model


View


Controller


Model

Ruby script/generate model Article


class Article < ActiveRecord::Base

end


Article.find(:all)

select * from articles

Article.find(1)

select * from articles where id = 1

Article.find(:first)

select * from articles limit 1

Article.find(:last)

select * from articles limit 1 order by id desc

Model

Article.find_all_by_title('test')

Article.find(:all, :conditions => “title = 'test'”)

Article.find(:all, :conditions => ['title =?', 'test'])

select * from articles where title = 'test'


Article.find(:all, :conditions => ['title =? AND author =
?', 'test', 'pero'])

select * from articles where title = 'test' and author = 'pero'


Article.find(:all, :order => 'created_at DESC')

select * from articles order_by created_at desc


Article.find(:all,:conditions => ['title =? AND author =
?', 'test', 'pero'], :order => 'created_at', :limit => 5)

Model

articles = Article.find(:all)

select * from articles

articles.count =>
1000

-

0.5s


Article.count

=>
1000

-

0.01s

select count(*) from articles


Article.count(:select => 'id')

=>
1000

-

0.00s

select count(id) from articles

Model

a = Article.new

a.title = 'Ovo je naslov'

a.author = 'Pero Perić'

a.created_at = Time.now

a.save

-------------------------------------------------
-------

data = {


:title => 'Ovo je naslov',


:author => 'Pero Perić',


:created_at => Time.now

}

a = Article.new(data)

a.save

Model

a = Article.find(1)

a.title = 'Ovo je novi naslov'

a.save

-----------------------------------------------------

a = Article.find(1)

a.destroy


ili

Article.find(1).destroy


Article.find(:all, :conditions => ['author ?',
'Pero']).destroy_all

Model

validates_presence_of :title, :message => 'Morate upisati naslov!'

validates_length_of :user_name, :within => 6..20, :too_long => "izaberite
kraće ime", :too_short => "izaberite duže ime"


validates_acceptance_of


prihvat

validates_associated


povezani objekti




validates_confirmation_of


potvrda unosa (npr. email)

validates_each




validacija više objekata

validates_exclusion_of


izuzetak

validates_format_of


format unosa

validates_inclusion_of


obrnuto od exclusion_of

validates_length_of


provjera dužine

validates_numericality_of


brojevi i provjere

validates_presence_of


prisutnost

validates_size_of


dužina

validates_uniqueness_of


jedinstveni unos

http://dizzy.co.uk/ruby_on_rails/cheatsheets/active
-
record
-
validations

Model

class Category < ActiveRecord::Base


has_many :articles, :dependent => :destroy

end

-----------------------------------------------

class Article < ActiveRecord::Base


belongs_to :category

end

-----------------------------------------------

article = Article.find(1)

article.title => Naslov članka

article.author => Autor članka

article.category.title => Naslov kategorije


Model

category = Category.find(1)

category.articles => svi članci koji pripadaju prvoj kategoriji


SELECT


*

FROM


categories, articles

WHERE


article.category_id = categories.id

Model




belongs_to

has_one

has_many

has_many :through

has_one :through

has_and_belongs_to_many

Model


belongs_to


class Order < ActiveRecord::Base


belongs_to :customer

end

Model


has_one


class Supplier < ActiveRecord::Base


has_one :account

end

Model


has_many

class Customer < ActiveRecord::Base


has_many :orders

end



Model

has_many :through

class Document < ActiveRecord::Base


has_many :sections


has_many :paragraphs, :through => :sections

end


class Section < ActiveRecord::Base


belongs_to :document


has_many :paragraphs

end


class Paragraph < ActiveRecord::Base


belongs_to :section

end

Model


has_one :through

class Supplier < ActiveRecord::Base


has_one :account


has_one :account_history, :through => :account

end


class Account < ActiveRecord::Base


belongs_to :supplier


has_one :account_history

end


class AccountHistory < ActiveRecord::Base


belongs_to :account

end

Model


has_and_belongs_to_many

class Assembly < ActiveRecord::Base


has_and_belongs_to_many :parts

end


class Part < ActiveRecord::Base


has_and_belongs_to_many :assemblies

end



http://guides.rubyonrails.org/association_basics.html

Model


has_and_belongs_to_many

class Assembly < ActiveRecord::Base


has_and_belongs_to_many :parts

end


class Part < ActiveRecord::Base


has_and_belongs_to_many :assemblies

end



http://guides.rubyonrails.org/association_basics.html

Model

named_scope :active,

:conditions => "show_forever='1' OR (from_date <=
CURRENT_DATE AND to_date > CURRENT_DATE)"



named_scope :archive, :conditions => "show_forever='0' OR (from_date >
CURRENT_DATE AND to_date <= CURRENT_DATE)"


----------------------------------------------------------------

Article.active

Article.archive

Model

def self.featured


find :all,


:select => 'title, created_at'


:conditions => 'featured = 1',


:order => 'id desc',



:limit => 6

end

----------------------------------------------------

Article.featured

Controller

class ArticlesController < ApplicationController


def index


end

end


-------------------------------------------------------------------

class ArticlesController < ApplicationController


def index


@page_title = “Homepage”


@articles = Article.find(:all)


end

end



Controller

class ArticlesController < ApplicationController


def show


@article = Article.find(params[:id])

end



www.site.com/articles/show/12

Controller

class ArticlesController < ApplicationController


def listing


if params[:type] == 'active'


@articles = Article.active


elsif params[:type] == 'archive'


@articles = Article.archive


else


@articles = Article.find(:all)


end


end

end


www.site.com/articles/listing?type=active


www.site.com/articles/listing?type=archive


www.site.com/articles/listing



Controller

class ArticlesController < ApplicationController


def login


session[:current_user_id] = params[:user_id]


end



def is_login


session[:current_user_id]


End



def logout


session[:current_user_id] = nil


end


end

Controller

params[:key] = “nesto”

session[:key] = “nesto”

flash[:key] = “nesto”


Npr. flash[:message] = 'Uspješno ste se logirali!'


<%= flash[:message] %>
-

prikazuje se samo jednom!


cookies[:key] = “nesto”


if params[:remeber_me]


cookies[:login] = { :value => "122", :expires => 1.year.from_now }

else


cookies[:login] = { :value => "122", :expires => 1.hour.from_now }

end

Controller

class ArticlesController < ApplicationController


layout 'administration'


before_filter :is_login



def index


end



def show


end




private




def is_login


session[:current_user_id]


end


end

Controller

class ArticlesController < ApplicationController




skip_before_filter :is_login, :only => [:index, :show]


ili


before_filter :is_login, :only => [:create, :edit, delete]




Metode: index, show, create, edit, delete



end

Controller


after_filter :after


around_filter :around


before_filter :before


Filter's chain:


...


.
\


. #around (code before yield)


. .
\


. . #before (actual filter code
is run)


. . .
\


. . .
execute controller
actions


. . . /


. . . /


. #around (code after yield)


. /


#after (actual filter code is run)

Controller

def index

end


=>
view/controller_name/index.html.erb


def index


render :text => "Zabranjen pristup!"

end


def update


render :action => 'edit'

end


def create


redirect_to :action => "index"

end


def index


@people = Person.find(:all)


respond_to do |format|


format.html
=> /index


format.xml { render :xml =>
@people.to_xml } => /index.xml


end

end


View



<% result = 5 + 5 %>

<%= result %>
-

<%= h result %>
-

<%=
raw result %>


<ul>


<% for article in @articles %>


<li><%= article.title %>


<% end %>

</ul>


<ul>


<li>prvi naslov</li>


<li>drugi naslov</li>


<li>....</li>

</ul>


View



<%= link_to “Login”, '/users/login'
%>

<%= link_to “Login”, :controller =>
'users', :action => 'login' %>


<a href=”/users/login”>Login</a>



<%= link_to “Login”, '/users/login',
:class => 'login_link' %>


<a href=”/users/login”
class=”login”>Login</a>



View

map.resources :articles

------------------------------

<%= link_to “new article”,
new_article_path %>

<a href=”/articles/new”>new
article</a>


new_article_path =>
'/articles/new' => create

articles_path =>
'/articles' => index

article_path(id) =>
'/articles/1' => show

edit_article_path(id) =>
'/articles/1/edit' => edit

article_path(id),


:method => 'delete' =>
'/articles/1' => destroy



map.resuources :categories do
|category|


category.resources :articles

end


category_articles_path(1) =>
'/categories/1/articles'

.....




View


def create


@article = Article.new

end


def update


@article = Article.find(1)

end

-------------------------------------
------------------


<% form_for :@article do |f| %>


<%= f.text_field :title %>


<%= f.text_area :content %>


<%= f.date_select :created_at %>


<%= submit_tag 'Snimi' %>

<% end %>


Isti ili partial template




View

image_tag("rails.png")


# => <img alt="Rails
src="/images/rails.png?1230601161"
/>



stylesheet_link_tag("application")


# => <link
href="/stylesheets/application.css?12322852
06" media="screen" rel="stylesheet"
type="text/css" />




stylesheet_link_tag :all, :cache =>
true # when
ActionController::Base.perform_cach
ing is false =>


<link
href="/stylesheets/style1.css"
media="screen" rel="stylesheet"
type="text/css" />


<link
href="/stylesheets/styleB.css"
media="screen" rel="stylesheet"
type="text/css" />


<link
href="/stylesheets/styleX2.css"
media="screen" rel="stylesheet"
type="text/css" />




javascript_include_tag "jQuery",
"default"


# =>


<script type="text/javascript"
src="/javascripts/jQuery.js"></scri
pt>


<script type="text/javascript"
src="/javascripts/default.js"></scr
ipt>



View


number_to_currency

number_to_human_size

number_to_percentage

number_to_phone

number_with_delimiter

number_with_precision

truncate

pluralize

distance_of_time_in_words

distance_of_time_in_words_to_now

time_ago_in_words

nas_vlastiti_helper



Zadatak


Knjižnica:



Knjige


* Kategorije


Članovi


Posudbe / povratak


Posuđene se ne mogu iznajmiti

-------------------------------------


Max. tri posudbe


Ako je duže od 30 dana, 1kn * dan
* knjiga


Top lista knjiga


Top lista članova


Tražilica



The end


Q&A


www.emusoft.hr

sloser@emusoft.hr

www.twitter.com/emusoft

http://groups.google.com/group/ruby
-
hr