Skip to content

Instantly share code, notes, and snippets.

@KefDS
Last active February 22, 2016 04:01
Show Gist options
  • Select an option

  • Save KefDS/13f890b1f6bc4b70b2aa to your computer and use it in GitHub Desktop.

Select an option

Save KefDS/13f890b1f6bc4b70b2aa to your computer and use it in GitHub Desktop.
Notas acerca del Framework Rails

Ruby on Rails

Inicio de un proyecto

  1. $ rails new MySite this command created a new Rails app named MySite. It generated a number of files and folders that we will use to build the app.

  2. $ bundle install This command installed all the software packages needed by the new Rails app. These software packages are called gems and they are listed in the file Gemfile.

  3. $ rails server command started the Rails development server so that we could preview the app in the browser by visiting http://localhost:8000 or http://localhost:3000. This development server is called WEBrick.

Request/Response cycle

  1. A user opens his browser, types in a URL, and presses Enter. When a user presses Enter, the browser makes a request for that URL.
  2. The request hits the Rails router (config/routes.rb).
  3. The router maps the URL to the correct controller and action to handle the request.
  4. The action receives the request, and asks the model to fetch data from the database. (Optional)
  5. The model returns a list of data to the controller action. (Optional)
  6. The controller action passes the data on to the view.
  7. The view renders the page as HTML.
  8. The controller sends the HTML back to the browser. The page loads and the user sees it. Diagrama More information: http://www.codecademy.com/articles/request-response-cycle-dynamic

Using the request/response cycle as a guide, this has been our workflow when making a Rails app.

  1. Generate a new Rails app.
  2. Generate a controller and add an action.
  3. Create a route that maps a URL to the controller action.
  4. Create a view with HTML and CSS.
  5. Run the local web server and preview the app in the browser.

Creating a controller

$ rails generate controller Pages command generated a new controller named Pages. This created a file named app/controllers/pages_controller.rb. Note: Use CamelCase

Methods in Rails controllers are also referred to as controller actions

Route

Now that we have a controller, let's move on to the second part of the request/response cycle and create a route.

Open config/routes.rb and type:

get 'welcome' => 'pages#home'

Now when a user visits http://localhost:8000/welcome, the route

get 'welcome' => 'pages#home'

will tell Rails to send this request to the Pages controller's home action.

View

En app/views/pages/home.html.erbse encontrará la vista.

Partials

Partes de código que se repiten en las mismas vistas del controlador o a nivel de todas las vistas. Inician con un _.

Creating a model

The rails generate model Message command created a new model named Message. In doing so, Rails created two files:

  • A model file in app/models/message.rb. The model represents a table in the database
  • A migration file in db/migrate/. Migrations are a way to update the database.
Migrate

Open the migration file in db/migrate/. The migration file contains a few things:

  • The change method tells Rails what change to make to the database. Here it uses the create_table method to create a new table in the database for storing messages.
  • Inside create_table, we added t.text :content. This will create a text column called content in the messages tables.
  • The final line t.timestamps is a Rails command that creates two more columns in the messages table called created_at and updated_at. These columns are automatically set when a message is created and updated.

Next The rake db:migrate command updates the database with the new messages data model.

Finally the rake db:seed command seeds the database with sample data from db/seeds.rb.

Standard Controller Actions

tabla More information: https://www.codecademy.com/articles/standard-controller-actions


Scaffold

Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

Example:

rails generate scaffold Product \
title:string description:text image_url:string price:decimal

Undo

In Rails, this can be accomplished with rails destroy followed by the name of the generated element. In particular, these two commands cancel each other out:

$ rails generate controller StaticPages home help
$ rails destroy controller StaticPages home help

Relaciones

Relaciones many to many

# Models
class Actor < ActiveRecord::Base
  has_many :parts
  has_many :movies, through: :parts
end

class Actor < ActiveRecord::Base
  has_many :parts
  has_many :movies, through: :parts
end

class Part < ActiveRecord::Base
  belongs_to :movie
  belongs_to :actor
end


# Migration (part)
class CreateParts < ActiveRecord::Migration
  def change
    create_table :parts do |t|
      t.belongs_to :movie, index: true # Llave foránea
      t.belongs_to :actor, index: true # Llave foránea
      t.timestamps
    end
  end
end

Varios temas

RSpec

Gemfile

group :development, :test do
	# ...
	# Testing

	# Includes RSpec itself in a wrapper to make it play nicely with Rails 3.
	gem 'rspec-rails'

	# Replaces Rails’ default fixtures for feeding test data to the test suite with much more preferable factories.
	gem 'factory_girl_rails'
end

group :test do
  # Generates names, email addresses, and other placeholders for factories.
  gem 'faker'

  # Makes it easy to programatically simulate your users’ interactions with your application.
  gem 'capybara'

  # Watches your application and tests and runs specs for you automatically when it detects changes.
  gem 'guard-rspec'

  # Does one thing, but does it well: It opens your default web browser upon failed integration specs to show you what your application is rendering.
  gem 'launchy'
end

Luego:

$ rails g rspec:install

En spec/spec_helper.rb poner:

require "capybara/rspec"

En .rspec poner --format documentation

En config/application.rb dentro de Application class

config.generators do |g|
  g.test_framework :rspec,
    :fixtures => true,
    :view_specs => false,
    :helper_specs => false,
    :routing_specs => false,
    :controller_specs => true,
    :request_specs => true
  g.fixture_replacement :factory_girl, :dir => "spec/factories"
end

Multilingual Inflector

# Rails 4
# insertar el siguiente código en config/initializers/inflections.rb
# You can now pass a locale as a parameter (defaults to :en)
ActiveSupport::Inflector.inflections(:es) do |inflect|
  inflect.plural(/$/, 's')
  inflect.plural(/([^aeéiou])$/i, '\1es')
  inflect.plural(/([aeiou]s)$/i, '\1')
  inflect.plural(/z$/i, 'ces')
  inflect.plural(/á([sn])$/i, 'a\1es')
  inflect.plural(/é([sn])$/i, 'e\1es')
  inflect.plural(/í([sn])$/i, 'i\1es')
  inflect.plural(/ó([sn])$/i, 'o\1es')
  inflect.plural(/ú([sn])$/i, 'u\1es')

  inflect.singular(/s$/, '')
  inflect.singular(/es$/, '')

  inflect.irregular('el', 'los')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment