Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Ruby / RailsРадослав СтанковVarna Lab                   14/07/2011
Кой съм аз?@rstankovhttp://rstankov.comhttp://blog.rstankov.comhttp://github.com/rstankov
RubyRuby е интерактивен,обектно-ориентиран език запрограмиране.Неготово мото е:“Optimized for programmer happiness”
Ruby on Rails   Ruby on Rails е framework   за уеб приложения.   Неготово мото е:   “Web development doesn’t hurt”
Ruby Създаден от японеца Юкихиро Мацумото „Мац“. Първата публична версия излиза през 1995. Версия 2.0 се очакава да излезе...
class System { // ... code ...    private $_categories = null;    public function getVisibleCategories() {      if ($this-...
class System # ... code ... def visible_categories()  return @categories ||= self.find_categories({:visible => t endend
class System # ... code ... def visible_categories()  return @categories ||= self.find_categories({:visible => t endend
class System # ... code ... def visible_categories  return @categories ||= self.find_categories({:visible => t endend
class System # ... code ... def visible_categories  return @categories ||= self.find_categories({:visible => t endend
class System # ... code ... def visible_categories  return @categories ||= self.find_categories({:visible => t endend
class System # ... code ... def visible_categories  @categories ||= self.find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= self.find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= self.find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= self.find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= find_categories({:visible => true}) endend
class System # ... code ... def visible_categories  @categories ||= find_categories :visible => true endend
5.times { puts "Ruby is cool!" }
5.times do  puts "Ruby is cool!"end
File.open("some_file.txt") do |file|  file << "content"end
[1,2,3,4].each { |value| puts value }# => [1, 2, 3, 4][1,2,3,4].map { |value| value * value }# => [1, 4, 9, 16][1,2,3,4].r...
def operate(value)  yield valueendvalue = operate(5) { |v| v + 4 }puts value # 9
class Person  attr_accessor :fist_name, :last_name  def initialize(first_name, last_name)    @first_name = first_name    @...
class Person  attr_accessor :fist_name, :last_name  def initialize(first_name, last_name)    @first_name = first_name    @...
class Person  attr_accessor :fist_name, :last_name  def initialize(first_name, last_name)    @first_name = first_name    @...
class Person  attr_accessor :fist_name, :last_name  def initialize(first_name, last_name)    @first_name = first_name    @...
class Person  attr_accessor :fist_name, :last_name  def initialize(first_name, last_name)    @first_name = first_name    @...
class Person  def +(other_person)    # ...  endendperson1 + person2
class Array  def first    self[0]  end  def second    self[1]  endendarray = [1, 2, 3, 4]array.first   # 1array.second # 2
class Numeric  def plus(x)    self + x  endendy = 5.plus(6)
Time.now - 2.days == 2.days.ago1.month.ago + 45.days - 1.year
Ruby•   димично определяне на типа данните•   модули•   отворени класове•   блокове•   анонимни функции•   всяка операция ...
Ruby on Rails          Разработен от David     Heinemeier Hansson от 37     Signals.     Първата публична версия е     изл...
37signals  Милиони клиенти ... по-малко от 37 служителя
Основни принципи на              Ruby on Rails•   Convention over Configuration•   DRY - Don’t Repeat Yourself•   KISS - Ke...
Основни принципи на              Ruby on Rails•   Convention over Configuration•   DRY - Don’t Repeat Yourself•   KISS - Ke...
MVC Архитектура
Начин на работа
RESTMethod         Path        Controller   Action  GET         /tasks         tasks       index  GET      /tasks/new     ...
Url формати Method          Path        Shows     Action  GET          /tasks/1       html      show  GET       /tasks/1.x...
Modelclass Task < ActiveRecord::Base  belongs_to :user  has_many :comments  validates_presence_of :user, :text  validates_...
Modelclass Task < ActiveRecord::Base  belongs_to :user  has_many :comments  validates_presence_of :user, :text  validates_...
Modelclass Task < ActiveRecord::Base  belongs_to :user  has_many :comments  validates_presence_of :user, :text  validates_...
Modelclass Task < ActiveRecord::Base  belongs_to :user  has_many :comments  validates_presence_of :user, :text  validates_...
Modelclass Task < ActiveRecord::Base  belongs_to :user  has_many :comments  validates_presence_of :user, :text  validates_...
Controllerclass TasksController < ApplicationController before_filter :require_user def index  @tasks = Task.where(:status ...
Controllerclass TasksController < ApplicationController before_filter :require_user def index  @tasks = Task.where(:status ...
Controllerclass TasksController < ApplicationController before_filter :require_user def index  @tasks = Task.where(:status ...
Controllerclass TasksController < ApplicationController before_filter :require_user def index  @tasks = Task.where(:status ...
Controllerclass TasksController < ApplicationController before_filter :require_user def index  @tasks = Task.where(:status ...
View<%= form_for task do |form| %> <%= render shared/error_messages, :target => form.object%> <p>  <%= form.label :text %>...
View + simple_form / slim = simple_form_for task do |form|  = form.error_banner  = form.input :text  = form.input :status,...
Test Driven Development
Test Driven Development1   Добавя се тест    ... за несъществуващ код
Test Driven Development1   Добавя се тест    ... за несъществуващ код                               2   Пише се код       ...
Test Driven Development    1     Добавя се тест          ... за несъществуващ код                                         ...
Test Driven Development    1     Добавя се тест          ... за несъществуващ код                                         ...
Cucumber featureFeature: Tasks In order to get more productive and organize As a user I want able to manage my tasks Scena...
Тесване на Controllerdescribe TasksController do  describe "GET show" do    before { Task.should_recive(:find).with("1").a...
describe Task do  it { should belong_to(:user) }  it { should have_many(:notes) } it { should validate_presence_of(:user) ...
Тестване на Viewdescribe "tasks/show.html.erb" do  before do    assign :task, mock_model(Task, {       :id   => 1,       :...
... и още, и още•   database migrations•   gem dependency management•   css/javascript management (from Rails 3.1)•   nest...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Погрешни схващания•   Rails CANT SCALE•   Rails is SLOW!!!!•   Hard to deploy•   Too much magic•   Hard to learn every thi...
Благодаря за вниманието@rstankov
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Ruby/Rails
Upcoming SlideShare
Loading in …5
×

Ruby/Rails

3,336 views

Published on

Моята презентация на тема Ruby/Rails за VarnaLab на

Published in: Technology
  • Be the first to comment

Ruby/Rails

  1. 1. Ruby / RailsРадослав СтанковVarna Lab 14/07/2011
  2. 2. Кой съм аз?@rstankovhttp://rstankov.comhttp://blog.rstankov.comhttp://github.com/rstankov
  3. 3. RubyRuby е интерактивен,обектно-ориентиран език запрограмиране.Неготово мото е:“Optimized for programmer happiness”
  4. 4. Ruby on Rails Ruby on Rails е framework за уеб приложения. Неготово мото е: “Web development doesn’t hurt”
  5. 5. Ruby Създаден от японеца Юкихиро Мацумото „Мац“. Първата публична версия излиза през 1995. Версия 2.0 се очакава да излезе за Коледа / не се казва коя /
  6. 6. class System { // ... code ... private $_categories = null; public function getVisibleCategories() { if ($this->_categories === null) { $this->_categories = $this->findCategories(array( visible => true )); } return $this->_categories; }}
  7. 7. class System # ... code ... def visible_categories() return @categories ||= self.find_categories({:visible => t endend
  8. 8. class System # ... code ... def visible_categories() return @categories ||= self.find_categories({:visible => t endend
  9. 9. class System # ... code ... def visible_categories return @categories ||= self.find_categories({:visible => t endend
  10. 10. class System # ... code ... def visible_categories return @categories ||= self.find_categories({:visible => t endend
  11. 11. class System # ... code ... def visible_categories return @categories ||= self.find_categories({:visible => t endend
  12. 12. class System # ... code ... def visible_categories @categories ||= self.find_categories({:visible => true}) endend
  13. 13. class System # ... code ... def visible_categories @categories ||= self.find_categories({:visible => true}) endend
  14. 14. class System # ... code ... def visible_categories @categories ||= self.find_categories({:visible => true}) endend
  15. 15. class System # ... code ... def visible_categories @categories ||= self.find_categories({:visible => true}) endend
  16. 16. class System # ... code ... def visible_categories @categories ||= find_categories({:visible => true}) endend
  17. 17. class System # ... code ... def visible_categories @categories ||= find_categories({:visible => true}) endend
  18. 18. class System # ... code ... def visible_categories @categories ||= find_categories :visible => true endend
  19. 19. 5.times { puts "Ruby is cool!" }
  20. 20. 5.times do puts "Ruby is cool!"end
  21. 21. File.open("some_file.txt") do |file| file << "content"end
  22. 22. [1,2,3,4].each { |value| puts value }# => [1, 2, 3, 4][1,2,3,4].map { |value| value * value }# => [1, 4, 9, 16][1,2,3,4].reduce { |a, b| a + b }# => 10[1,2] * 3# => [1, 2, 1, 2, 1, 2]
  23. 23. def operate(value) yield valueendvalue = operate(5) { |v| v + 4 }puts value # 9
  24. 24. class Person attr_accessor :fist_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name first_name + " " + last_name endendme = Person.new("Radoslav", "Stankov")puts me.full_name # Radoslav Stankov
  25. 25. class Person attr_accessor :fist_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name first_name + " " + last_name endendme = Person.new("Radoslav", "Stankov")puts me.full_name # Radoslav Stankov
  26. 26. class Person attr_accessor :fist_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name first_name + " " + last_name endendme = Person.new("Radoslav", "Stankov")puts me.full_name # Radoslav Stankov
  27. 27. class Person attr_accessor :fist_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name first_name + " " + last_name endendme = Person.new("Radoslav", "Stankov")puts me.full_name # Radoslav Stankov
  28. 28. class Person attr_accessor :fist_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end def full_name first_name + " " + last_name endendme = Person.new("Radoslav", "Stankov")puts me.full_name # Radoslav Stankov
  29. 29. class Person def +(other_person) # ... endendperson1 + person2
  30. 30. class Array def first self[0] end def second self[1] endendarray = [1, 2, 3, 4]array.first # 1array.second # 2
  31. 31. class Numeric def plus(x) self + x endendy = 5.plus(6)
  32. 32. Time.now - 2.days == 2.days.ago1.month.ago + 45.days - 1.year
  33. 33. Ruby• димично определяне на типа данните• модули• отворени класове• блокове• анонимни функции• всяка операция връща резултат• всичко е изпълним код• изчистен синтаксис• мета програмиране• промяна на обектите по време на изпълнение• вградени регулярни изрази
  34. 34. Ruby on Rails Разработен от David Heinemeier Hansson от 37 Signals. Първата публична версия е излиза през юли 2004. Вървим бавно, но сигурно към 3.1
  35. 35. 37signals Милиони клиенти ... по-малко от 37 служителя
  36. 36. Основни принципи на Ruby on Rails• Convention over Configuration• DRY - Don’t Repeat Yourself• KISS - Keep it simple, Stupid!• Skinny Controller, Fat Model• Тest Driven Development / Behavior Driven Development• Less is More• Code Generation• REST
  37. 37. Основни принципи на Ruby on Rails• Convention over Configuration• DRY - Don’t Repeat Yourself• KISS - Keep it simple, Stupid!• Skinny Controller, Fat Model• Тest Driven Development / Behavior Driven Development• Less is More• Code Generation• REST N ! VE FU HA
  38. 38. MVC Архитектура
  39. 39. Начин на работа
  40. 40. RESTMethod Path Controller Action GET /tasks tasks index GET /tasks/new tasks new POST /tasks tasks create GET /tasks/:id tasks show GET /tasks/:id/edit tasks edit PUT /tasks/:id tasks updateDELETE /tasks/:id tasks delete
  41. 41. Url формати Method Path Shows Action GET /tasks/1 html show GET /tasks/1.xml xml show GET /tasks/1.json json show GET /tasks/1.print html show PUT /tasks/1 redirect updatePUT(xhr) /tasks/1 html/js update PUT /tasks/1.json json update
  42. 42. Modelclass Task < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user, :text validates_inclusion_of :status, :in => ["opened", "completed"] attr_readonly :user_id def editable? status == "opened" endend
  43. 43. Modelclass Task < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user, :text validates_inclusion_of :status, :in => ["opened", "completed"] attr_readonly :user_id def editable? status == "opened" endend
  44. 44. Modelclass Task < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user, :text validates_inclusion_of :status, :in => ["opened", "completed"] attr_readonly :user_id def editable? status == "opened" endend
  45. 45. Modelclass Task < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user, :text validates_inclusion_of :status, :in => ["opened", "completed"] attr_readonly :user_id def editable? status == "opened" endend
  46. 46. Modelclass Task < ActiveRecord::Base belongs_to :user has_many :comments validates_presence_of :user, :text validates_inclusion_of :status, :in => ["opened", "completed"] attr_readonly :user_id def editable? status == "opened" endend
  47. 47. Controllerclass TasksController < ApplicationController before_filter :require_user def index @tasks = Task.where(:status => "opened") end def show @task = Task.find(params[:id]) end def create @task = current_user.tasks.build(params[:task]) if @task.save redirect_to tasks_path else render :partial => "new" end endend
  48. 48. Controllerclass TasksController < ApplicationController before_filter :require_user def index @tasks = Task.where(:status => "opened") end def show @task = Task.find(params[:id]) end def create @task = current_user.tasks.build(params[:task]) if @task.save redirect_to tasks_path else render :partial => "new" end endend
  49. 49. Controllerclass TasksController < ApplicationController before_filter :require_user def index @tasks = Task.where(:status => "opened") end def show @task = Task.find(params[:id]) end def create @task = current_user.tasks.build(params[:task]) if @task.save redirect_to tasks_path else render :partial => "new" end endend
  50. 50. Controllerclass TasksController < ApplicationController before_filter :require_user def index @tasks = Task.where(:status => "opened") end def show @task = Task.find(params[:id]) end def create @task = current_user.tasks.build(params[:task]) if @task.save redirect_to tasks_path else render :partial => "new" end endend
  51. 51. Controllerclass TasksController < ApplicationController before_filter :require_user def index @tasks = Task.where(:status => "opened") end def show @task = Task.find(params[:id]) end def create @task = current_user.tasks.build(params[:task]) if @task.save redirect_to tasks_path else render :partial => "new" end endend
  52. 52. View<%= form_for task do |form| %> <%= render shared/error_messages, :target => form.object%> <p> <%= form.label :text %> <%= form.text_area :text %> </p> <p> <%= form.label :status %> <%= form.select :status, Task.statuses %> </p> <div class="buttons"> <%= form.submit %> | <% link_to "Cancel", tasks_path %> </div><% end %>
  53. 53. View + simple_form / slim = simple_form_for task do |form| = form.error_banner = form.input :text = form.input :status, :collection => Task.statuses .buttons = form.submit = link_to Cancel, tasks_path
  54. 54. Test Driven Development
  55. 55. Test Driven Development1 Добавя се тест ... за несъществуващ код
  56. 56. Test Driven Development1 Добавя се тест ... за несъществуващ код 2 Пише се код ... колкото само тестът да мине
  57. 57. Test Driven Development 1 Добавя се тест ... за несъществуващ код 2 Пише се код ... колкото само тестът да мине3 Правят се подобрения ... подобрява се качеството на кода
  58. 58. Test Driven Development 1 Добавя се тест ... за несъществуващ код 2 Пише се код ... колкото само тестът да мине3 Правят се подобрения ... подобрява се качеството на кода
  59. 59. Cucumber featureFeature: Tasks In order to get more productive and organize As a user I want able to manage my tasks Scenario: Adding tasks Given I am on the tasks page When I follow "New task" And I fill in "Text" with "Present Ruby" And I select "opened" from "Status" And I press "Create task" Then I should have opened task "Present Ruby" Scenario: Completing tasks Given I am on the tasks page And I have opened task "Present Ruby" When I follow "Edit tasks" And I select "completed" from "Status" And I press "Update task" Then I should have completed task "Present Ruby"
  60. 60. Тесване на Controllerdescribe TasksController do describe "GET show" do before { Task.should_recive(:find).with("1").and_return task } before { get :show, :id => "1" } it { should assign_to(:task).with(task) } it { should render_temlate("show") } endend
  61. 61. describe Task do it { should belong_to(:user) } it { should have_many(:notes) } it { should validate_presence_of(:user) } it { should validate_presence_of(:text) } describe "#editable?" do it "returns true if task status is opened" do Task.new(:status => "opened").should be_editable end it "returns false if task status is rejected" do Task.new(:status => "rejected").should_not be_editable end it "returns false if task status is completed" do Task.new(:status => "completed").should_not be_editable end endend
  62. 62. Тестване на Viewdescribe "tasks/show.html.erb" do before do assign :task, mock_model(Task, { :id => 1, :text => "task text" }) render end it "renders task text" do rendered.should contain("task text") end it "renders link for editing task" do rendered.should have_selector(a[href="/tasks/1/edit"]) endend
  63. 63. ... и още, и още• database migrations• gem dependency management• css/javascript management (from Rails 3.1)• nested forms• automatic deploys• Rack• generations• send/receive mails• caching• internalization (i18n)• Ruby language extentions• a LOT plugins, tools and services• ... и т.н.
  64. 64. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  65. 65. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  66. 66. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  67. 67. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  68. 68. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  69. 69. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  70. 70. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  71. 71. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  72. 72. Погрешни схващания• Rails CANT SCALE• Rails is SLOW!!!!• Hard to deploy• Too much magic• Hard to learn every thing• Impossible to extend rails!• No good IDE• Bad windows support• Documentation
  73. 73. Благодаря за вниманието@rstankov

×