02/28/21

Install Docker and Rails on Debian

Part 1: Docker auf einem frischen Debian Server installieren

  1. Install Docker Engine on Debian
  2. Install Docker Compose
  3. Quickstart: Compose and Rails || da ich lieber MySQL nutzen will: Setting up Ruby on Rails with docker and MySQL
    1. Aus den dockerdocs habe ich folgende Zeile übernommen für die docker-compose.yml: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" Erklärung: server.pid löschen, da das sonst oft zu Problemen führt beim Start.

12/1/16

RVM und Apache

Manage Ruby Versions and gem-packages

Mit RVM kann man pro Anwendung individuelle Railsversionen und gem-Packete definieren, die verwendet werden sollen. Extrem praktisch, um z.B. ein Projekt mit neuen Ruby oder Railsversionen zu testen oder umgekehrt dem Updatezwang zu entgehen.

Einführung in RVM

Ruby 2.1.1 installieren und benutzen

$ rvm install 2.1.1
$ rvm use 2.1.1

Um wieder das Default System-Ruby ohne rvm zu nutzen:

$ rvm use system

Gemsets Basics

Erst werden 1 oder mehrere (leere) gemsets erstellt.
Dann wird ein gemset mit der Rubyversion aktiviert. Dann können für dieses gemset gems installiert werden.

$ rvm gemset create rails410 rails320
Gemset 'rails410' created.
Gemset 'rails320' created.

$ rvm 2.1.1@rails410
$ gem install rails -v 4.1.0

$ rvm 2.1.1@rails320
$ gem install rails -v 3.2.0

Gemset erstellen und nutzen
rvm --create use 1.8.7@some-gemset-name
gem install rails -v 2.3.14

Infos zu den Gemsets:
Name des aktuelles Gemsets

$rvm gemset name

Show path des aktuellen gemsets

$rvm gemdir

Auflisten aller gemsets (für den aktuellen Rubyintepreter, alle)

$rvm list
$rvm list_all

 

RVM in Entwicklungsumgebung

myproject$ rvm 2.1.1@rails320
myproject$ ./script/server

Lädt das richtige gemset und startet den mongrel Testserver, der dann auf die Development_DB zugreift.

RVM in Apache

Ausführliche Behandlung des Themas

Unter sites-available in der x.conf den Pfad zum RVM-gemset angeben:

<VirtualHost *:80>
    PassengerRuby /usr/local/rvm/wrappers/ruby-1.9.3-p551@rails2318/ruby
...
</VirtualHost>
05/5/13

Ruby on Rails

Inhalt

  1. Tutorials und Referenzen
  2. Tools and Environment
    1. But What Does It All Mean
    2. Testtools
    3. GIT – Version controll
  3. Entwicklungszyklus
  4. Themen und Komponenten
    1. Rake
    2. Plugin annotate models
    3. Controller – Action – Parameter
    4. ORM – Objekt relational mapping
    5. Ruby
    6. Validation von Modelparametern
    7. Associating models
    8. Rails Helper
    9. Fileupload
    10. Ajax
  5. Facebooker
  6. Spickzettel

 

 

1. Tutorials und Referenzen

Ruby on Rails Tutorial
– Chapter 1 From zero to deploy
– Chapter 3 Rails-flavored Ruby
 

Ruby on Rails Guide

Rail API

Ruby Einführung und Dokumentation

Ruby-page

Ruby-Core

 

galileo openbook: ruby_on_rails08

Starting Ruby on Rails: What I Wish I Knew

Rails-sourcen: http://rubyforge.org/frs/?group_id=307
zum Inhalt

2. Tools and Environment

Here’s the tools you’ll need. Don’t read endless reviews trying to decide on the best one; start somewhere and get going.

2.1 But What Does It All Mean?

Ruby is a programming language, similar to Python and Perl. It is dynamically typed (no need for “int i”), interpreted, and can be modified at runtime (such as adding new methods to classes).
Ruby API

Rails is a gem, or a Ruby library.
Rails API

IRB is the interactive Ruby console (type “irb” to use). Rails has a special IRB console to access your web app as it is running (excellent for live debugging): apps/blog>ruby script/console

Rake is Ruby’s version of Make. Define and run maintenance tasks like setting up databases, reloading data, backing up, or even deploying an app to your website.

Erb is embedded Ruby, which is like PHP. It lets you mix Ruby with HTML (for example):


Hello there, <%= get_user_name() %>

YAML (or YML) means “YAML Ain’t a Markup Language” — it’s a simple way to specify data:

{name: John Smith, age: 33}

It’s like JSON

Eclipse

 

O’Reilly: Ruby on Rails Meets Eclipse (2007)

2.2 Testtools

irb – interactive ruby bash

rubyfähigen Terminal öffnen (z.B. per Locomotive)

apps/blog>irb

Befehle zeilenweise eingeben:

irb(main):012:0> tmp = [[1,2],[3,4]]
=> [[1, 2], [3, 4]]
irb(main):007:0> for i in tmp
irb(main):008:1> i[0] = 11
irb(main):009:1> end
=> [[11, 2], [11, 4]]

Ruby Console

irb für das aktuelle Projekt: Rails invokes Ruby’s irb utility in the context of your Rails application

rubyfähigen Terminal in Projekt öffnen (z.B. per Locomotive)

apps/blog>ruby script/console

 

Loading development environment (Rails 2.1.1)
>>

Jetzt Rubybefehle zeilenweise

2.3 GIT – Version controll

siehe GIT

zum Inhalt

3. Entwicklungszyklus

  • apps>rails blog -d mysql
    • erzeugt neue Anwendung “blog”
  • apps/blog>rake db:create
    • erzeugt die passende Datenbank “blog_development”
  • apps/blog>script/generate controller home index
    • erzeugt den controller home mit der action index
    • Anwendung kann jetzt getestet werden – Standartstartseite
  • apps/blog>rm public/index.html
    • in config/routes folgendes vor map.connect ergänzen
      map.root :controller => “home”
    • Anwendung kann jetzt getestet werden – Startseite = home/index
  • apps/blog>script/generate scaffold Post name:string title:string content:text
    • erzeugt MVC-Standartfiles für Manipulation von Model Post
  • apps/blog>rake db:migrate
    • erzeugt alle Tabellen aus den Models, bzw. aus den migrationfiles
  • Link ergänzen: apps/blog/app/views/home/index.html.erb editieren
    • <%= link_to "My Blog", posts_path %>
    • Anwendung kann jetzt getestet werden – Startseite = home/index – dem Link folgen
  • apps/blog>rake doc:app
    • Erzeugt Documentation unter doc/app/
  • Controller und Models einzeln hinzufügen
    • apps/blog>ruby script/generate [controller|model|migration] yourname
  • Migration editieren: 
    blog/db/migrate/20090321142337_create_channels.rb
  • apps/blog>rake db:migrate


zum Inhalt

4. Themen und Komponenten

4.1 rake

DB Migration

>rake db:migrate

>rake db:migrate VERSION=10

> ruby script/generate scaffold

Freezing Rails

Speichert alle verwendeten gems in vendor/rails und nutzt diese statt des Lokalen Rails

>rake rails:freeze:gems
>rake rails:unfreeze

Weitere Infos


zum Inhalt

4.2 Plugin annotate_models

1.download+install (for each project):
planner>ruby script/plugin install http://repo.pragprog.com/svn/Public/plugins/annotate_models

2.run:
planner>rake annotate_models


zum Inhalt

4.3 Controller – Action – Parameter

http://my.url/store/add_to_cart/123
In this simple case, it takes the first part of the path, store, as the
name of the controller and the second part, add_to_cart, as the name of an
action. The last part of the path, 123, is by convention extracted into an internal
parameter called id.


zum Inhalt

4.4 ORM-object relational mapping

So an ORM layer maps tables to classes, rows to objects, and columns to
attributes of those objects. Class methods are used to perform table-level operations,
and instance methods perform operations on the individual rows.


zum Inhalt

4.5 Ruby

Types of variables
name local variable ‘name’
@name instance variable ‘name’
:name Symbol ‘name’

Instance variables are nil if not defined, while local var not defined leads to an error.
Ruby symbol
link_to “Goodbye!” , :action => “goodbye”
The :action part is a Ruby symbol. You can think of the colon as meaning
the thing named…, so :action means the thing named action.7 The => “goodbye”
associates the string goodbye with the name action. In effect, this gives us
keyword parameters for methods.

Arrays

a = [42, 8, 17]

a << “foo” << “bar” # Chaining array pushes
=> [42, 8, 17, 7, “foo”, “bar”]

>> (0..9).to_a # Use parentheses to call to_a on the range

=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>> a.sort_by { rand }

array = array.split(/,\s*/)

array2 = []

array.in_groups_of(6) {|item| array2 << item }

puts array2[2][0]

Hashes

>> user = {}                          # {} is an empty hash
=> {}
>> user["first_name"] = "Michael"     # Key "first_name", value "Michael"
=> "Michael"
>> user["last_name"] = "Hartl"        # Key "last_name", value "Hartl"
=> "Hartl"
>> user["first_name"]                 # Element access is like arrays
=> "Michael"
>> user                               # A literal representation of the hash
=> {"last_name"=>"Hartl", "first_name"=>"Michael"}
>> user = { "first_name" => "Michael", "last_name" => "Hartl" }

better use symbols

>> user = { :name => "Michael Hartl", :email => "
 michael@example.com" }
=> {:name=>"Michael Hartl", :email=>"
 michael@example.com"}
>> user[:name]              # Access the value corresponding to :name.
=> "Michael Hartl"
>> user[:password]          # Access the value of an undefined key.
=> nil

Multidim hashes

>> params = {}        # We'll start with the strategically named params hash.
=> {}
>> params[:user] = { :name => "Michael Hartl", :email => "
 mhartl@example.com" }
=> {:name=>"Michael Hartl", :email=>"
 mhartl@example.com"}
>> params
=> {:user=>{:name=>"Michael Hartl", :email=>"
 mhartl@example.com"}}
>>  params[:user][:email]
=> "
 mhartl@example.com"

 

Generelle Regeln

– Ruby functions have an implicit return, meaning they return the last statement evaluated

– Ruby also has an explicit return option; using first return if if-statement is true:

>> def string_message(string)
>>   return "It's an empty string!" if string.empty?
>>   return "The string is nonempty."
>> end

Auch explizit und implizit möglich:

>> def string_message(string)
>>   return "It's an empty string!" if string.empty?
>>   "The string is nonempty."
>> end

Parameter for functions

# Parentheses on function calls are optional.
stylesheet_link_tag('blueprint/screen', :media => 'screen')
stylesheet_link_tag 'blueprint/screen', :media => 'screen'
# Curly braces on final hash arguments are optional.
stylesheet_link_tag 'blueprint/screen', { :media => 'screen' }
stylesheet_link_tag 'blueprint/screen', :media => 'screen'

Klassen, Funktionen und Methoden

Methods: Functions provided by an instance variable

>> class Word
>>   def palindrome?(string)
>>     string == string.reverse
>>   end
>> end

>> w = Word.new              # Make a new Word object
>> w.palindrome?("level")
=> true

Using Inheritance

Here Word < String is the Ruby syntax for inheritance, which ensures that, in addition to the new palindrome? method, words also have all the same methods as strings

>> class Word < String             # Word inherits from String
>>   # Return true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse             # self is the string itself
>>   end
>> end

>> s = Word.new("level")    # Make a new Word, initialized with "level".
=> "level"                  
>> s.palindrome?            # Words have the palindrome? method.
=> true                     
>> s.length                 # Words also inherit all the normal string methods.
=> 5

Klassen überschreiben

>> class String
>>   # Return true if the string is its own reverse.
>>   def palindrome?
>>     self == self.reverse
>>   end
>> end
=> nil
>> "deified".palindrome?
=> true

 

Modules

– module ApplicationHelper: code in Ruby modules can be mixed in to Ruby classes. When writing ordinary Ruby, you often write modules and include them explicitly yourself, but in this case Rails handles the inclusion automatically for us.

 


zum Inhalt

4.6 Validation von Modelparametern

class Post < ActiveRecord::Base
validates_presence_of :name, :title
validates_length_of :title, :minimum => 5
end

zum Inhalt

4..7 Associating Models

1:n

class Product < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :product
end
1:1

class Order < ActiveRecord::Base
has_one :invoice
end

n:m

class Article < ActiveRecord::Base
has_and_belongs_to_many :users
# …
end

class User < ActiveRecord::Base
has_and_belongs_to_many :articles
# …
end


zum Inhalt

4.8 Rails-Helper

(see all at Rails Framework Doc)
helper is a function designed for use in views.

<% for item in @items %>
<% for column in Item.content_columns %>
<%=h item.send(column.name) %>
<% end %>
<%= link_to ‘Show’, :action => ‘show’, :id => item %>
<%= link_to ‘Edit’, :action => ‘edit’, :id => item %>
<%= link_to ‘Destroy’, { :action => ‘destroy’, :id => item }, :confirm => ‘Are you sure?’, :method => :post %>
<% end %>

<%= link_to image_tag(‘delete.png’), { :action => ‘destroy’, :id => @entry, :start => @root, :layout => @layout }, :confirm => ‘Are you sure?’, :method => :post %>

 

<%= link_to image_tag(‘Einstellungen.gif’, :width => 50, :border => 0), :controller => ‘settings’, :action => ‘list’ %>

<%= stylesheet_link_tag ‘scaffold’ %>


zum Inhalt

4.9 Fileupload

HowtoUploadFiles


zum Inhalt

 

4.10 AJAX

depot_l/app/views/layouts/store.rhtml

<%= stylesheet_link_tag “depot” , :media => “all” %>
<%= javascript_include_tag :defaults %>

depot_l/app/views/store/add_to_cart.rjs
page.replace_html(“cart” , :partial => “cart” , :object => @cart)

depot_l/app/controllers/store_controller.rb
def add_to_cart
begin
product = Product.find(params[:id])
rescue
ActiveRecord::RecordNotFound
logger.error(“Attempt to access invalid product #{params[:id]}” )
redirect_to_index(“Invalid product” )
else
@cart = find_cart
@cart.add_product(product)
end
end

depot_l/app/views/store/index.rhtml
<% form_remote_tag :url => { :action => :add_to_cart, :id => product } do %>
<%= submit_tag “Add to Cart” %>
<% end %>


zum Inhalt

5. Facebooker

Facebooker Pretutorial

Facebooker offizielles Tutorial

Facebooker-API


zum Inhalt

6. Spickzettel

http://www.addedbytes.com/download/ruby-on-rails-cheat-sheet-v1/png/