Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Wednesday, November 6, 2013

Ruby: exceptions

raise "Exception message" // this will throw RuntimeError exception with message "Exception message"

begin
  10/0 // This will raise an DivisionByZero exception
rescue DivisionByZero
  puts "Devision by zero exception"
end
Creating custom exception:
class CustomException > StandardError
end

Ruby: OOP (privacy)

Methods are public by default in Ruby.

class Test

  def public_m
  end

  private
  def private_m
  end

  // Again private method, because all methods after private keyword will be private
  def private_m_2
  end

end
Modules are containers for methods and constants.

module MyModule
  // Call it: MyModule::MOD_CONSTANT
  MOD_CONSTANT = "Module constat"

  // Call it: MyModule.my_method
  def my_method
  end
end
Require module by typing require 'MyModule', so it will be available in whole file (Module.my_method)

Include module to class, so it will be available inside class and all the methods can be called without module name:


class SimpleClass
  include MyModule // Without '
  def m
    my_method
  end
end
Infromation from: www.codeacademy.com

Ruby: OOP (Basic)

class Person
  // This is a variable, that belongs to class
  // Like static variable in PHP
  @@class_variable = 0

  // This is a global variable
  $global_var

  // This is a constructor
  def initialize(name)
    // @name - class variable, name - local variable
    // @name will be available in whole class
    @name = name
    @class_variable += 1
  end

  // This is method, that belongs to class not to instance!
  // Like static method in PHP
  def self.class_method
  end
end

// This will create 2 instances of a Person class
andy = Person.new("Andy")
marrel = Person.new("Marrel")
// @@class_variable on this step will be equals to 2

Inheritance
// Class andy inherits all from class Person
class Andy < Person
  def initialize(name)
    // This will call parent initialize method
    super(name)
  end
end 

Infromation from: www.codeacademy.com 

Ruby: procs and lambdas

Procs:
Sometimes you need to pass block to your method. The problem is that you cant save block to variable, because it is not an object. If you need to pass one block to many methods, there's no need to the same block over and over again, because you can make Proc. Proc saves your block to variable, and gives you an opportunity to manipulate with it like with object.

proc_name = Proc.new { your block here }

func1(&proc_name)
func2 &proc_name
You must pass proc to method with & symbol.

Also you can convert symbols to procs using magic & symbol:
(function .map and .collect runs through all the elements in array)
number = [0,1,2]
number.map(&:to_s) // This will convert 0,1,2 to strings
Lambda:Lambdas are almost the same as procs, with the exception of syntax and few behavioral features.

Proc.new { puts "Hello" }
same as
lambda { puts "Hello!" }
Differencies between lambdas and procs:
1. Lambda checks the number of arguments passed to it, while a proc does not. Lambda will throw an error, proc will assign nil to all unassigned arguments.
2.When a lambda returns, it passes control back to the calling method; when a proc returns, it returns immediately, whithout passing control back.

// Outputs "Hello world!"
def A
  h = Proc.new { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

// Outputs "Hello galaxy!"
def B
  h = lambda { return "Hello world!" }
  h.call
  return "Hello galaxy!"
end

Infromation from: www.codeacademy.com

Tuesday, November 5, 2013

Ruby interesting things

puts "Hello" if statement == true // This construction works fine, and puts "Hello" if statement equals to true, but construction if statement == true puts "Hello" will cause an error.

26.respond_to?(:next)   // .next() method will return next value to 26. This contruction will return true, because method next can be applied to 26 (.next method will return 27, by the way)

5.times {} // Will run block 5 times

5.upto(10) { |num| puts num } // Will return 5 6 7 8 9 10 on each line (.downto(n) works other way round)

[1,2,3]  << 4 // Will return [1,2,3,4] also works on strings "Andy" << " Marrel" -> "Andy Marrel"

"String " + 26 // Will cause error, because you neet to cast 26 to string, but you can apply string interpolation, so the string will be ok -> "String #{26}"

Information from: www.codeacademy.com

Wednesday, October 2, 2013

Ruby first

Before i'll start learning ruby on rails framework, i'm going to learn some basics of ruby language.

Variables:

hello_world = "";
variable = 10;

Methods:

def method_name
  return "Something";
end

def method_name(arg1, arg2)
  puts arg1.to_s + " " + arg2.to_s;
end

Classes:

class ClassName
  // Constructor
  def initialize
    @price = 30
  end

  // Variable @price and getter of price
  def price
    @price
  end

  // Setter of price.
  def price=(value)
    @price = value
  end
end

vari = ClassName.new;
puts vari.price; // Prints 30
vari.price = 10; // Same as vari.price=(10)
puts vari.price; // Prints 10

class ClassName
  attr_reader :price; // Same as getter. attr_reader :price, :weight, :lol;
  attr_writer :price;  // Same as setter
  //attr_accessor :price; // This method creates getters and setters together.
end

Anonymous functions (blocks)

yield :)

Tuesday, October 1, 2013

Ruby on Rails (novice)

Установить ноде.жиесть т.к. могут возникнуть ошибки.
Создание каркаса (модель вид и контроллер) одной командой:  rails generate scaffold Product title:string description:string price:decimal image_url:string

Данная команда создаёт модель, различные виды, контроллер, миграцию и т.д. Далее можно отредактировать миграцию (db/migrate/TIMESTAMP_migration.rb), которая впоследствии внесёт изменения в нашу бд через команду (rake db:migrate - вносит изменения в бд из миграций, которые ещё не были задействованы)

Удалить каркас можно командой: rails destroy scaffold Product

Sunday, September 29, 2013

Installing Ruby + Rails on Windows 8 x64

1. Download and install Rubyinstaller (Ruby 2.0.0-p247 (x64) for me, you can try another version) from http://rubyinstaller.org/downloads/
2. Download and install Ruby Dev Kit (DevKit-mingw64-64-4.7.2-20130224-1432-sfx.exe for me) from http://rubyinstaller.org/downloads/

You can type in cmd or in cmd for ruby command "ruby --version" to check your ruby version.
Also you can check already installed gems by typing: "gem list --local" or "gem list --local rails" to check if rails already installed (for me it wasn't).

NB! You may need to configure your RubyDevKit to run "gem install rails". First of all you need to cd in command prompt to your rubydevkit root; then you need to run those cmds:
ruby dk.rb init
ruby dk.rb install

3. In cmd (or cmd for ruby) type "gem install rails"

After rails was installed, we need to install Sqlite 3 (the most difficult part of installation ^^), because rails use it as a default db engine. The problem is that we need to compile sqlite from source codes manually.
Now we will be using instructions, that was written by "paulwis" in this topic  https://github.com/luislavena/sqlite3-ruby/issues/82.
Also thanks to this topic: http://stackoverflow.com/questions/15480381/how-do-i-install-sqlite3-for-ruby-on-windows

4. Download source files of SQLite (sqlite-autoconf-3080002.tar.gz) and extract it somwhere ("C:/Sqlite/src/" for example.)
5. Open msys.bat file from RubyDevKit folder and change location using "cd" command to your sqlite source dir (for me it was "cd /C:/Sqlite/src/")
6. Run command "./configure"
7. Run command "make"
8. Run command "make install"
9. Now you need to install sqlite gem. Run command
"gem install sqlite3 --platform=ruby -- --with-sqlite3-include=[path\to\sqlite3.h] --with-sqlite3-lib=[path\to\sqlite3.o]"
for me it was:
"gem install sqlite3 --platform=ruby -- --with-sqlite3-include=/C:/Sqlite/src --with-sqlite3-lib=/C:/Sqlite/src/.libs/"
10. By the end you can check Gemfile.lock (in your rails application), if your version is correct. Make sure, that sqlite points to right version of ruby. Sometimes it needs to be changed for example from "sqlite3 (1.3.7-x86-mingw32)" to "sqlite3 (1.3.7-x64-mingw32)" or "sqlite3 (1.3.7)".

Now we can check our rails application. If it was not created yet, open command prompt or cmd for ruby, run "cd" to your applications folder (it can be any folder you prefer, f.e. "C:/MyRailsApps/" so you will run in cmd "cd C:/MyRailsApps/"). After run "rails new Hello_world" to create your Hello_world app. Than "cd Hello_world" and run "rails server". If all was ok, you can look at your app here: http://localhost:3000