Skip to content

Instantly share code, notes, and snippets.

@blaisethomas
Created August 29, 2015 20:09
Show Gist options
  • Save blaisethomas/efe6d97127ccc1018177 to your computer and use it in GitHub Desktop.
Save blaisethomas/efe6d97127ccc1018177 to your computer and use it in GitHub Desktop.

#INTRO

So far we have looked at how to make apps in RUBY.

  1. We can build individual example.rb files that each have a specific use
  2. We can run these in the command line $ ruby example.rb
  3. We can require them between each other, to combine them
  4. Using the structure of classes we can share objects and their behaviors && inherit from other classes

:( the only downside is that our apps have not had a nice shiny and fun UI and our outputs have been boring and from the command line. Good thing we already learned how to do this in HTML, CSS and JS


Imagine something that allows us to combine all this fun ruby stuff, and make it serve up some HTML, CSS and JS documents.

The content (from our DB and ruby code) can be completly customized based on who is logged in (profile picture // news feed) and packaged up:

"bespoke HTML CSS and JS " with private or user specific content.


###Genius


###Lets play with rails.


#RAILS

Rails is a framework for Ruby that provides us with lots of great tools.

Things to know about Rails:

  1. Convention over customization.
  2. ModelViewController
  3. Testing
  4. It has a CLI we can play with. DO NOT MAKE NOTES!!

DO AS MUCH AS YOU CAN FROM THE COMMAND LINE!!!!! There is a built in manual for everything. use -h or --help to access the manual. These should have all the notes that you need!

Once rails is installed, from ANYWHERE within your workspace you can

###$ rails -h

Try it out!


This returns to you your first set of instructions, let's break them down:

Usage:
  rails new APP_PATH [options] 

CAPITAL_LETTERS in the documentation denote a VARIABLE that we can specify

There are also many [options] that we can specify. Let's start with these...


Options:
  
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library
  
  -T, [--skip-test-unit], [--no-skip-test-unit]          # Skip Test::Unit files
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file

Also the usual help options:

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

###Let's try it out:

###$ rails new coffee_shop -d=postgresql

This generates a skeletal Rails installation in a new directory "coffee_shop" with a postgresql database. It will generate approx 40 files across 40 directories: Let's take a moment to look around, focusing on the app directory.


.
├── Gemfile
├── Gemfile.lock
├── README.rdoc
├── Rakefile
├── app
│   ├── assets
│   │   ├── images
│   │   ├── javascripts
│   │   │   └── application.js
│   │   └── stylesheets
│   │       └── application.css
│   ├── controllers
│   │   ├── application_controller.rb
│   │   └── concerns
│   ├── helpers
│   │   └── application_helper.rb
│   ├── mailers
│   ├── models
│   │   └── concerns
│   └── views
│       └── layouts
│           └── application.html.erb
├── bin
│   ├── bundle
│   ├── rails
│   ├── rake
│   ├── setup
│   └── spring
├── config
│   ├── application.rb
│   ├── boot.rb
│   ├── database.yml
│   ├── environment.rb
│   ├── environments
│   │   ├── development.rb
│   │   ├── production.rb
│   │   └── test.rb
│   ├── initializers
│   │   ├── assets.rb
│   │   ├── backtrace_silencers.rb
│   │   ├── cookies_serializer.rb
│   │   ├── filter_parameter_logging.rb
│   │   ├── inflections.rb
│   │   ├── mime_types.rb
│   │   ├── session_store.rb
│   │   └── wrap_parameters.rb
│   ├── locales
│   │   └── en.yml
│   ├── routes.rb
│   └── secrets.yml
├── config.ru
├── db
│   └── seeds.rb
├── lib
│   ├── assets
│   └── tasks
├── log
│   └── development.log
├── public
│   ├── 404.html
│   ├── 422.html
│   ├── 500.html
│   ├── favicon.ico
│   └── robots.txt
├── test
│   ├── controllers
│   ├── fixtures
│   ├── helpers
│   ├── integration
│   ├── mailers
│   ├── models
│   └── test_helper.rb
├── tmp
│   └── cache
│       └── assets
├── tree.txt
└── vendor
    └── assets
        ├── javascripts
        └── stylesheets

38 directories, 42 files


###Before we do anything else

###$ cd coffee_shop

and then we can do this again

###$ rails -h

Notice that this time, the result of our $ rails -h is very different... Because we are INSIDE a rails app.


Usage: rails COMMAND [ARGS]

**All commands can be run with -h (or --help) for more information.**

The most common rails commands are:
 generate    Generate new code (short-cut alias: "g")
 console     Start the Rails console (short-cut alias: "c")
 server      Start the Rails server (short-cut alias: "s")
 dbconsole   Start a console for the database specified in config/database.yml
             (short-cut alias: "db")
 new         Create a new Rails application. "rails new my_app" creates a
             new application called MyApp in "./my_app"
             DONT DO IT!!! No need for a rails app within a rails app! (For now)

In addition to those, there are:
 destroy      Undo code generated with "generate" (short-cut alias: "d")


All commands can be run with -h (or --help) for more information.

lets try each of them:

###$ rails console -h

This is our interactive ruby console. It is IRB with the addition of inheriting our whole ruby app.

###$ rails server -h

This fires up our rails server

###$ rails dbconsole -h

This allows us to view our PostgreSQL DB and query it with SQL


###$ rails generate -h

Usage: rails generate GENERATOR [args] [options]

Can also be abbreviated to "rails g"

General options:
  -h, [--help]     # Print generator's options and usage

Modified list: (these will be the most useful)

GENERATORS
  controller
  helper
  mailer
  migration
  model
  scaffold

Notice Model & Controller Generators


Generators are a useful tool that generate directories, files and even code, within the structure of our Rails app (and puts everything in the right place -- remember RAILS CONVENTION). $ rails new is our starting point generator, and it generates the ground work for our whole app.

We now have the option of using more generators. Let's start with the M in MVC.

And lets also start with reading the manual, as usual:


###$ rails generate model -h

Usage:
  rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
  


Description:
    Stubs out a new model. Pass the model name, either CamelCased or
    under_scored, and an optional list of attribute pairs as arguments.

    Attribute pairs are field:type arguments specifying the
    model's attributes. Timestamps are added by default, so you don't have to
    specify them by hand as 'created_at:datetime updated_at:datetime'.

    As a special case, specifying 'password:digest' will generate a
    password_digest field of string type, and configure your generated model and
    tests for use with ActiveModel has_secure_password (assuming the default ORM
    and test framework are being used).

    You don't have to think up every attribute up front, but it helps to
    sketch out a few so you can start working with the model immediately.

    This generator invokes your configured ORM and test framework, which
    defaults to ActiveRecord and TestUnit.

Available field types:

    Just after the field name you can specify a type like text or boolean.
    It will generate the column with the associated SQL type. For instance:

        `rails generate model post title:string body:text`

    will generate a title column with a varchar type and a body column with a text
    type. If no type is specified the string type will be used by default.
    You can use the following types:

        integer
        primary_key
        decimal
        float
        boolean
        binary
        string
        text
        date
        time
        datetime

    You can also consider `references` as a kind of type. For instance, if you run:

        `rails generate model photo title:string album:references`

    It will generate an `album_id` column. You should generate these kinds of fields when
    you will use a `belongs_to` association, for instance. 

    If you require a `password_digest` string column for use with
    has_secure_password, you should specify `password:digest`:

        `rails generate model user password:digest`

Examples:
    `rails generate model account`

        For ActiveRecord and TestUnit it creates:

            Model:      app/models/account.rb
            Test:       test/models/account_test.rb
            Fixtures:   test/fixtures/accounts.yml
            Migration:  db/migrate/XXX_create_accounts.rb

    `rails generate model post title:string body:text published:boolean`

        Creates a Post model with a string title, text body, and published flag.

    `rails generate model admin/account`

        For ActiveRecord and TestUnit it creates:

            Module:     app/models/admin.rb
            Model:      app/models/admin/account.rb
            Test:       test/models/admin/account_test.rb
            Fixtures:   test/fixtures/admin/accounts.yml
            Migration:  db/migrate/XXX_create_admin_accounts.rb


###$ rails generate controller -h

Usage:
  rails generate controller NAME [action action] [options]

Options:
      [--skip-namespace], [--no-skip-namespace]  # Skip namespace (affects only isolated applications)
      [--skip-routes], [--no-skip-routes]        # Don't add routes to config/routes.rb.
  -e, [--template-engine=NAME]                   # Template engine to be invoked
                                                 # Default: erb
  -t, [--test-framework=NAME]                    # Test framework to be invoked
                                                 # Default: test_unit
      [--helper]                                 # Indicates when to generate helper
                                                 # Default: true
      [--assets]                                 # Indicates when to generate assets
                                                 # Default: true

Description:
    Stubs out a new controller and its views. Pass the controller name, either
    CamelCased or under_scored, and a list of views as arguments.

    To create a controller within a module, specify the controller name as a
    path like 'parent_module/controller_name'.

    This generates a controller class in app/controllers and invokes helper,
    template engine, assets, and test framework generators.

Example:
    `rails generate controller CreditCards open debit credit close`

    CreditCards controller with URLs like /credit_cards/debit.
        Controller: app/controllers/credit_cards_controller.rb
        Test:       test/controllers/credit_cards_controller_test.rb
        Views:      app/views/credit_cards/debit.html.erb [...]
        Helper:     app/helpers/credit_cards_helper.rb

###$ rails generate scaffold -h

Usage:
  rails generate scaffold NAME [field[:type][:index] field[:type][:index]] [options]

Options:
      [--skip-namespace], [--no-skip-namespace]  # Skip namespace (affects only isolated applications)
      [--force-plural], [--no-force-plural]      # Forces the use of the given model name
  -o, --orm=NAME                                 # Orm to be invoked
                                                 # Default: active_record
      [--model-name=MODEL_NAME]                  # ModelName to be used
      [--resource-route], [--no-resource-route]  # Indicates when to generate resource route
                                                 # Default: true
  -y, [--stylesheets], [--no-stylesheets]        # Generate Stylesheets
                                                 # Default: true
  -se, [--stylesheet-engine=STYLESHEET_ENGINE]   # Engine for Stylesheets
                                                 # Default: scss
      [--assets], [--no-assets]                  # Indicates when to generate assets
                                                 # Default: true
  -c, --scaffold-controller=NAME                 # Scaffold controller to be invoked
                                                 # Default: scaffold_controller


ActiveRecord options:
      [--migration], [--no-migration]    # Indicates when to generate migration
                                         # Default: true
      [--timestamps], [--no-timestamps]  # Indicates when to generate timestamps
                                         # Default: true
      [--parent=PARENT]                  # The parent class for the generated model
      [--indexes], [--no-indexes]        # Add indexes for references and belongs_to columns
                                         # Default: true
  -t, [--test-framework=NAME]            # Test framework to be invoked
                                         # Default: test_unit

TestUnit options:
      [--fixture], [--no-fixture]   # Indicates when to generate fixture
                                    # Default: true
  -r, [--fixture-replacement=NAME]  # Fixture replacement to be invoked

ScaffoldController options:
      [--helper], [--no-helper]  # Indicates when to generate helper
                                 # Default: true
  -e, [--template-engine=NAME]   # Template engine to be invoked
                                 # Default: erb
      [--jbuilder]               # Indicates when to generate jbuilder
                                 # Default: true

Asset options:
  -j, [--javascripts], [--no-javascripts]       # Generate JavaScripts
                                                # Default: true
  -je, [--javascript-engine=JAVASCRIPT_ENGINE]  # Engine for JavaScripts
                                                # Default: coffee

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Description:
    Scaffolds an entire resource, from model and migration to controller and
    views, along with a full test suite. The resource is ready to use as a
    starting point for your RESTful, resource-oriented application.

    Pass the name of the model (in singular form), either CamelCased or
    under_scored, as the first argument, and an optional list of attribute
    pairs.

    Attributes are field arguments specifying the model's attributes. You can
    optionally pass the type and an index to each field. For instance:
    'title body:text tracking_id:integer:uniq' will generate a title field of
    string type, a body with text type and a tracking_id as an integer with an
    unique index. "index" could also be given instead of "uniq" if one desires
    a non unique index.

    As a special case, specifying 'password:digest' will generate a
    password_digest field of string type, and configure your generated model,
    controller, views, and test suite for use with ActiveModel
    has_secure_password (assuming they are using Rails defaults).

    Timestamps are added by default, so you don't have to specify them by hand
    as 'created_at:datetime updated_at:datetime'.

    You don't have to think up every attribute up front, but it helps to
    sketch out a few so you can start working with the resource immediately.

    For example, 'scaffold post title body:text published:boolean' gives
    you a model with those three attributes, a controller that handles
    the create/show/update/destroy, forms to create and edit your posts, and
    an index that lists them all, as well as a resources :posts declaration
    in config/routes.rb.

    If you want to remove all the generated files, run
    'rails destroy scaffold ModelName'.

Examples:
    `rails generate scaffold post`
    `rails generate scaffold post title body:text published:boolean`
    `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq`
    `rails generate scaffold user email:uniq password:digest`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment