background preloader

Ruby

Facebook Twitter

Commencer avec Ruby on Rails. Ce guide s'inspire du site « Rails Guides », de mon expérience personnelle de Ruby on Rails et dans tout un tas d'autres ressources (screencasts, sites communautaires, etc...). Ce guide est également l'occasion de constituer une application de A à Z, d'en voir tous les tenants et les aboutissants (conception, codage, déploiement, etc...). Je vous souhaite d'ores et déjà une très bonne lecture ! Dans ce guide, je pars du principe que le lecteur possède une connaissance minimale du langage Ruby. Si certaines portions de code Ruby nécessitent des précisions, j'expliquerai le plus clairement possible ces points de détail. Pour commencer avec Ruby on Rails, il est nécessaire d'avoir au moins trois choses installées : Ruby (version 1.8.7 dans le cas de ce guide) Rubygems (version 1.3.2 dans le cas de ce guide) SQLite, MySQL, ou PostgreSQL Rails est un framework de développement web écrit en langage Ruby.

La philosophie de Rails se base sur trois principes : III-A. III-B. IV-A. IV-B. IV-C. #135 Making a Gem. #336 Copycopter. Copycopter provides a nice interface that clients can use to edit the text in a Rails application. Learn how to deploy a Copycopter server using Heroku and integrate it in a Rails application through I18n. Download: source codeProject Files in Zip (84.4 KB)mp4Full Size H.264 Video (20.9 MB)m4vSmaller H.264 Video (9.79 MB)webmFull Size VP8 Video (9.75 MB)ogvFull Size Theora Video (20.8 MB) #264 Guard. Guard watches files and runs a command after a file is modified. This allows you to automatically run tests in the background, restart your development server, reload the browser, and more. Download: source codeProject Files in Zip (260 KB)mp4Full Size H.264 Video (17 MB)m4vSmaller H.264 Video (10.5 MB)webmFull Size VP8 Video (24.8 MB)ogvFull Size Theora Video (23.6 MB)

Setting up PostgreSQL for Ruby on Rails development on OS X | Will writes. One of the reasons people used to give for using MySQL over PostgreSQL (just ‘Postgres’ from here on in) was that Postgres was considered hard to install. It’s a shame, because it’s a great database (I’ve been using it for personal and some work projects for years, like my current side project, sendcat). Luckily it’s now really simple to get it going on your Mac to give it a try. This is how you do it. What this guide is This is a guide to getting PostgreSQL running locally on your Mac, then configuring Rails to use that for development. What this guide is not An advanced PostgreSQL guide.Suitable for using in production.Anything to do with why you might want to use PostgreSQL over any other database. Installation You can get binaries for most systems from the Postgresql site, but it’s even easier if you’ve got homebrew installed, if you haven’t got homebrew it’s worth it, pick it up here.

With homebrew just run: $ brew install postgres brew info postgres $ initdb /usr/local/var/postgres Done!

Débutant

Getting Started with Rails. 1 Guide Assumptions This guide is designed for beginners who want to get started with a Rails application from scratch. It does not assume that you have any prior experience with Rails. Rails is a web application framework running on the Ruby programming language. If you have no prior experience with Ruby, you will find a very steep learning curve diving straight into Rails. There are several curated lists of online resources for learning Ruby: Be aware that some resources, while still excellent, cover versions of Ruby as old as 1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day development with Rails. 2 What is Rails? Rails is a web application development framework written in the Ruby programming language. Rails is opinionated software. The Rails philosophy includes two major guiding principles: 3 Creating a New Rails Project The best way to read this guide is to follow it step by step. 3.1 Installing Rails Open up a command line prompt. 4 Hello, Rails!

Phusion Passenger application server. Pradeep's Ruby on Rails Blog | RoR for developers. Asset Pipeline. 1 What is the Asset Pipeline? The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages and pre-processors such as CoffeeScript, Sass and ERB. The asset pipeline is technically no longer a core feature of Rails 4, it has been extracted out of the framework into the sprockets-rails gem. The asset pipeline is enabled by default. You can disable the asset pipeline while creating a new application by passing the --skip-sprockets option. Rails 4 automatically adds the sass-rails, coffee-rails and uglifier gems to your Gemfile, which are used by Sprockets for asset compression: Using the --skip-sprockets option will prevent Rails 4 from adding sass-rails and uglifier to Gemfile, so if you later want to enable the asset pipeline you will have to add those gems to your Gemfile. 1.1 Main Features The second feature of the asset pipeline is asset minification or compression.

More reading: Comment reprendre un (gros) projet Ruby on Rails. Sublime Text: Convert Ruby 1.8 to 1.9 style hash syntax. Updated for Rails 3: Using Paperclip and jpegcam to get pictures from your webcam into Rails. View the complete source code for this post Here’s how to get pictures from your webcam into Rails using the Paperclip plugin and jpegcam.

It is an update of the Rails 2.3.x version of this post. What we will do is create a Photo model and a Photos controller with actions new, upload and create to take care of the image creation. Start by creating a new Rails application: Create the Photo model: Create the Photos controller: Edit config/routes.rb to contain a photos resource: Download jpegcam and put webcam.js in your public/javascripts folder and webcam.swf and shutter.mp3 in your public folder. Edit the layout file app/views/layouts/application.html.erb and insert the following HTML inside the <head>-tag just below the other javascript_include_tag: Next, create app/views/photos/new.html.erb and make a div for the webcam contents: And the actual webcam javascript: That will run the actual webcam so you can see yourself :) But for taking a picture, we’ll need to add the following button: Then run:

Decaf : Ruby in the Browser. Www.urubatan.com.br/wp-content/uploads/2011/10/quick_ref_view_helpers.pdf. Création d'un blog avec le framework Padrino - 1ère partie : les bases | Julien Itard - Blog. A l’heure où j’écris ces lignes, Padrino est en v 0.11.0. Si ce n’est déjà fait, je vous invite à lire mon article présentant ce framework. Dans cette première partie du tutoriel consacré à la réalisation d’un blog à l’aide du framework Padrino, nous allons poser les bases de notre application qui servira de support à votre apprentissage. Sources Vous pouvez retrouver les sources finales de cet article ici. Les identifiants de l’administration sont : adresse mail : admin@admin.commot de passe : admin Installation Avant de commencer à développer notre application, vous devez avoir préalablement installé sur votre poste Ruby ainsi que Rubygems.

Pour plus d’informations sur l’installation, je vous invite à consulter le guide officiel. Génération du projet Pour créer un projet sous Padrino, la meilleure chose à faire est d’utilisée le générateur en ligne de commande qui est extrêmement pratique en bien des situations. . $ padrino g project blog -e haml -c sass -s jquery -d activerecord -b Conclusion. Tutorial Rubyonrails 3 - Partie 3 - Création des relations entre les models (détail relation et migration) - Développeur Web RoR.

Partie 3 – Rails3 - Création des relations entre les models (détail relation et migration) N’hésitez à mettre des commentaires / à corriger mes fautes / à rajouter des choses ! Rails intègre un système de migration. Chaque migration et un fichier ruby qui modife la structure de la base de données. Donc si vous avez besoin de renommer un champ, de rajouter une table, de rajouter un champ, de supprimer un champ vous devez créer une migration.

Les migrations se trouvent dans monblog/db/migrate . Pourquoi parler des migrations ? Eh bien, nous avons les models, nous savons les manipuler. Souvenez-vous dans la partie 2 : reader : celui qui laissera un ou plusieurs comments sur un post. post : un article du blog, il possède plusieurs comments. comment : les commentaires des readers sur un post. Nous allons donc créer une migration pour ajouter les clés étrangères oubliées (volontairement) lors du rails generate model. Ouvrons le fichier (monblog/db/migrate/XXXXXXXXXXXXX_add_foreign_keys.rb): Ruby on Rails 1.2.2, les migrations. Voici la suite du précédent tutoriel sur Ruby on Rails publié sur ce même blog ou nous avons mis en place une application de gestion de contacts rudimentaire. Migration de schéma de base de données Imaginons que nous voulions gérer une liste de sociétés, et lier chacun de nos contacts à sa société...

Il va nous falloir modifier notre base de données en ajoutant une table companies et une clé company_id dans la table contacts. Cela peut s'avérer compliqué puisqu'elle contient déjà des données... même si en l'occurence il ne s'agit pour l'heure que de données de test. Rails et plus particulièrement ActiveRecord proposent un outil de gestion des évolutions du modèle de données intelligent, les migrations. Au même titre que nous avions créé le fichier db/migrate/001_contacts_development.rb pour définir le schéma initial lors du tutoriel précédent, nous allons maintenant créer son évolution incrémentale dans le fichier db/migrate/002_contacts_development.rb : Puis, dans le fichier . Le fichier . Migrations. 1 Migration Overview Migrations are a convenient way to alter your database schema over time in a consistent and easy way.

They use a Ruby DSL so that you don't have to write SQL by hand, allowing your schema and changes to be database independent. You can think of each migration as being a new 'version' of the database. A schema starts off with nothing in it, and each migration modifies it to add or remove tables, columns, or entries. Here's an example of a migration: This migration adds a table called products with a string column called name and a text column called description. Note that we define the change that we want to happen moving forward in time. On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction.

There are certain queries that can't run inside a transaction. If you wish for a migration to do something that Active Record doesn't know how to reverse, you can use reversible: 2 Creating a Migration will generate. Svenfuchs/i18n. I18n extra translations. Ruby dispose d’une large palette de bibliothèques. Parmi ce qu’il y a de plus indispensable on compte l’internationalisation, ou i18n. La référence est l’implémentation de Sven Fuchs. C’est cette gem qui est utilisée par Rails pour traiter tout ce qui concerne l’i18n.

Objectifs Dans cet article je vais étendre les fonctionnalités d’i18n. Modifier le backend Rails utilise par défaut I18n::Backend::Simple pour les traductions. En effet, nous allons étendre le backend pour qu’il intercepte et enregistre tout les appels à translate et si oui ou non il ont échoués. L’idée est d’arriver à surcharger la methode translate originale avec : Dans un premier temps on va créer une classe Store qui va permette de stocker les clés de traduction. La méthode translate utilise les paramètres : locale, key et options. Les deux one-liners avec inject sont plus complexes, ils réalisent tout deux une exploration en profondeur pour : rechercher une clé (used?) Rapport à la fin des tests require '. Conclusion. Vos scripts ruby avec ARGF. À l’écriture d’un script ruby on a tendance à utiliser ARGV, pour lire les paramètres entrants.

Généralement cela représente le chemin d’un fichier. Admettons que je veuille un script tout simple qui rajoute le numéro de chaque ligne: Un appel type . /pipe.rb datas.csv fonctionne très bien mais comment faire en sorte que mon script soit réutilisable et que je puisse lui passer du contenu en entrée type: $ echo "foo,bar\nbaz,coin" | . Nous avons besoin que notre script suive les principes UNIX et puisse être utilisé avec des pipes, en sortie ou en entrée. Pour cela nous avons à disposition ARGF. La sortie (STDOUT) de echo va directement venir alimenter l’entrée de notre script ruby (STDIN) avec le résultat suivant: echo "foo,bar\nbaz,coin" | .

À noter que cela fonctionne également avec un tail -f, exemple: $ tail -f feed.csv | . De la même façon la sortie de notre script peut être réutilisée dans l’entrée d’un utilitaire GNU. cat datas.csv | . J’espère que ces quelques lignes de Ruby (5!)

Gem

Programmation Ruby/Syntaxe. Un livre de Wikilivres. << Retour au sommaire La syntaxe de ruby est à la fois simple, car elle permet de lire simplement le code source, et complexe, car à la manière du perl il y a plusieurs manières d'écrire une même instruction. Nomenclatures[modifier | modifier le wikicode] Notons que par nomenclature les méthodes terminant par un point d'exclamation !

Sont non pures : elles modifient l'objet. Identifiants[modifier | modifier le wikicode] Tout nom (que cela soit pour les variables, méthodes, classes...) doit respecter une certaine nomenclature : tout identifiant doit commencer soit par une lettre, soit par un souligné (_), et bien sur ne doit pas être un des mots réservés du langage. Exemples : MaVariables => Ok _maVariable => Ok 3Variables => Erreur [modifier | modifier le wikicode] En Ruby, les commentaires peuvent prendre deux formes.

#Ceci est un commentaire # ceci est un# bloc de# commentaire puts "toto" # ce commentaire suit une instruction exemple : exemple: Exemple : donc : Par contre : The 10 Most Underused ActiveRecord::Relation Methods - Mitch Crowe. Knee-deep in ActiveRecord::Relation code yesterday, I was reminded of some interesting nuggets that I’ve seen used far too rarely. Here, I’ve gathered my top ten most underused relation methods from that list for your reading delight. 10. first_or_create with a block first_or_create is very familiar: and does exactly what it says.

Often, though, you want to find a record with certain attributes, or create one with those and additional attributes. 9. first_or_initialize If you don’t want to save the record yet, you can use first_or_initialize: 8. scoped Sometimes you want an ActiveRecord::Relation representing all the records of a class. 7. none (rails 4 only) Likewise, sometimes you want an ActiveRecord::Relation that contains no objects.

Note: You have to be seriously living on the edge to use none right now. 6. find_each If you want to iterate over thousands of records, you probably don’t want to use each. Note that you can’t specify the order of records yielded by find_each. 3. scoping. Ruby on Rake, ou comment Rake m'a rendu alcoolique. Know Your Options! ActiveRecord::Relation vs Arel. #239 ActiveRecord::Relation Walkthrough. Ruby on Rails Guides: Débuter avec Rails. Ici et ailleurs » Ruby on Rails : Conventions, mappage basique et migrations.