Skip to content

Instantly share code, notes, and snippets.

@jendiamond
Last active March 18, 2016 23:03
Show Gist options
  • Select an option

  • Save jendiamond/b9e52efd45a1bea6c85b to your computer and use it in GitHub Desktop.

Select an option

Save jendiamond/b9e52efd45a1bea6c85b to your computer and use it in GitHub Desktop.

edit spec - http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html

$ rails_best_practices .

Sublime tutorial

https://scotch.io/bar-talk/the-complete-visual-guide-to-sublime-text-3-getting-started-and-keyboard-shortcuts

http://code.tutsplus.com/articles/perfect-workflow-in-sublime-text-free-course--net-27293

Fun Club Tutorial with Test Driven Development

https://www.digitalocean.com/community/tutorials/how-to-setup-ruby-on-rails-with-postgres

  • $ rails new funclub --database=postgresql
  • $ cd funclub
  • $ git init
  • $ git add .
  • $ git commit -m 'Initial commit'
  • $ git remote add origin [email protected]:jendiamond/funclub.git
  • $ git push -u origin master

https://infinum.co/the-capsized-eight/articles/top-8-tools-for-ruby-on-rails-code-optimization-and-cleanup
https://github.com/aanand/deadweight

Add RSpec-Railsfor Testing

Gemfile

gem 'rspec-rails', '~> 3.4', '>= 3.4.2'

===

  • $ bundle
  • $ rails generate rspec:install

===

.rspec

--color
--warnings
--require spec_helper
  • Git Flow

Add Simplecov for Testing

  1. Add the gem to your Gemfile gem 'simplecov', :require => false, :group => :test

  2. Load and launch SimpleCov at the very top of your test/test_helper.rb or spec_helper.rb They must be the first two lines of your test_helper should be like this:

require 'simplecov'
SimpleCov.start 'rails'
  1. Run your tests, open up coverage/index.html in your browser and check out what you've missed so far.

  2. Add the following to your .gitignore file to ensure that coverage results are not tracked by Git (optional):

coverage


Add Database Cleaner for testing


Add Coveralls for testing


  • Delete any extraneous files
  • Git Flow

.gitignore
app/assets/javascripts/application.js
app/assets/stylesheets/application.css
app/controllers/application_controller.rb
app/controllers/concerns/.keep
app/mailers/.keep
app/models/concerns/.keep
bin/setup
config/application.rb
config/database.yml
config/environment.rb
config/environments/development.rb
config/environments/production.rb
config/environments/test.rb
config/initializers/assets.rb
config/initializers/backtrace_silencers.rb
config/initializers/cookies_serializer.rb
config/initializers/filter_parameter_logging.rb
config/initializers/inflections.rb
config/initializers/mime_types.rb
config/initializers/session_store.rb
config/initializers/wrap_parameters.rb
config/locales/en.yml
config/routes.rb
config/secrets.yml
log/.keep
spec/spec_helper.rb
test/controllers/.keep
test/fixtures/.keep
test/helpers/.keep
test/integration/.keep
test/mailers/.keep
test/models/.keep
test/test_helper.rb
vendor/assets/javascripts/.keep
vendor/assets/stylesheets/.keep


Create Workout Model

$ rails g model Workout date_time:datetime activity:string location:string description:text

$ rake db:migrate


Create a Seed File

ACTIVITY = ['calisthenics', 'bike', 'hike', 'yoga', 'rest']  
LOCATION = ['Vista Hermosa Natural Park', 'Mountain Lion Loop',
            'Carosel Loop', 'Atwater Village', 'Stay Home']  
DESCRIPTION = ['Do the snake.', 'Take on trash truck hill.',
               'Get to the bridge.', 'Hot and sweaty',
               'Let your muscles rebuild.']

5.times do |i|
  Workout.create(
      date_time: Date.today.strftime("%A, %B %d %I:%M %P"),
      activity: ACTIVITY[i],
      location: LOCATION[i],
      description: DESCRIPTION[i]
      )
end

http://www.foragoodstrftime.com/


Add rails_best_practices gem to check the quality of my Rails code.

In the root of the terminal run
$ rails_best_practices .


$ rails g controller Workouts


Test

gem 'rails_best_practices', '~> 1.16'

spec/requests/workouts_spec.rb

require 'rails_helper'

describe 'workouts', type: :request do

  describe 'GET #index' do
    Workout.create(
    date_time: "2016-03-05 18:09:47",
    activity: "Bike",
    location: "Griffith Park",
    description: "Training Ride")

    it 'returns http success' do
      get '/workouts'
      expect(response).to have_http_status(200)
      expect(response).to render_template('index')
    end
  end
end

Add Factory Girl and Refactor Tests

Add FactoryGirl-Rails & Ffaker for Testing

Gemfile

gem 'factory_girl_rails', '~> 4.5'
gem 'ffaker', '~> 2.2'
Configure your test suite - ?To Ad or not to Add?

spec/support/factory_girl.rb

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
end

===

spec/factories/workouts.rb

FactoryGirl.define do
  factory :workout do
    date_time { Date.today.strftime("%A, %B %d %I:%M %P") }
    activity { FFaker::Sport.name }
    location { FFaker::AddressUS.neighborhood }
    description { FFaker::HipsterIpsum.words(4).join(',') }
  end
end

auto-generated:

FactoryGirl.define do
  factory :workout do
    date "2016-03-02"
    time "2016-03-02 18:09:47"
    activity "MyString"
    location "MyString"
    description "MyText"
  end
end

Create Routes and View for Index

config/routes.rb

Rails.application.routes.draw do
  resources :workouts, only: index
  root "workouts#index'
end

Update the README

### Calisthenic Fun Club

I have a workout club with my friends I called Calisthenic Fun Club.
Instead of joining a gym we workout together.
+ We keep the workouts fun
+ We get to hang out together
+ We inspire each other
I used to email everyone on Sunday to tell them the schedule for the week.
This app will make it much easier to make the schedule. 
Plus I can track our workouts over time.

---

### Installation and usage

bundle install
bundle exec rspec

---

Rails version             4.2.5  
Ruby version              2.3.0-p0 (x86_64-linux)  
RubyGems version          2.5.1  
Rack version              1.6.4  
Database Development      SQLite3  
Database Production       Postgres  
JavaScript Runtime        Node.js (V8)  
Middleware                Rack

---

#### Add Postgres and rails_12factor to Gemfile to push to Heroku

**`Gemfile`**  

group :development do gem 'sqlite3' end

group :production do gem 'pg' gem 'rails_12factor' end


$ `bundle`

---

#### Add Bootstrap

**`Gemfile`**  
`gem 'bootstrap-sass', '~> 3.3', '>= 3.3.5.1'`

$ `bundle`

**app/assets/javascript**  

//= require jquery //= require jquery_ujs //= require bootstrap-sprockets //= require turbolinks //= require_tree .


**`app/assets/styslesheets`**  

/* *= require_tree . *= require_self */ @import "bootstrap-sprockets"; @import "bootstrap";


---

**`workouts_controller.rb`**  

class WorkoutsController < ApplicationController def index end end


===

**`workouts/index.html`**  
`<%= Workout Index %>`

---

### Test

**`spec/requests/workouts_spec.rb`**

describe 'GET /workouts/new' do it 'should render a new workout template' do get '/workouts/new' expect(response).to have_http_status(200) expect(response).to render_template('new') end

describe 'POST /markets' it 'should create a new workout' do expect { post '/workouts', workout: { date_time: workout.date_time, activity: workout.activity, location: workout.location, description: workout.description } }.to change(Workout, :count).by(1) expect(response).to have_http_status(302) expect(response).to redirect_to(workout_url(Workout.last.id)) end end


---

### Add ability to create a New Workout

**`workouts_controller.rb`**  

class WorkoutsController < ApplicationController def index end

def new @workout = Workout.new end

def create @workout = Workout.new(workout_params) if @ workout.save redirect_to @workout else render 'new' end end

private def workout_params params.require(:workout).permit(:date_time :activity :location :description) end end


---

### Add New Workout


**`app/views/workouts/new.html.erb`**  

<%= New Workout %>

render 'form'

link_to 'Cancel', root_path


### Add New Workout


**`app/views/workouts/_form.html.erb`**  

<%= New Workout %>

render 'form'

link_to 'Cancel', root_path


#### Add simpleform to Gemfile

`gem 'simple_form', '~> 3.2', '>= 3.2.1'`

$ `bundle`  
$ `rails g simple_form:install --bootstrap`

Inside your views, use the `simple_form_for` with one of the Bootstrap form
  classes, `.form-horizontal` or `.form-inline`, as the following:

`= simple_form_for(@user, html: { class: 'form-horizontal' }) do |form|`

---

http://stevenyue.com/2013/03/23/date-time-datetime-in-ruby-and-rails/  
http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm  
https://github.com/plataformatec/simple_form
http://stackoverflow.com/questions/21855709/simple-form-radio-button

**`workouts/_form.html`**  

<%= simple_form_for(@workout, html: {class: 'form-horizontal'}) do |f| %>

<%= f.input :date_time, label: "Date & Time" %>
<%= f.input :activity, collection: ['calisthenics', 'bike', 'hike','yoga', 'rest'] %> <%= f.input :location, label: "Location", input_html: { class: "form-control" } %>
<%= f.input :description, label: "Description", input_html: { class: "form-control" } %>

<%= f.submit %>

<% end %> ```
Added this to get the select tags of date_time in one div

app/inputs/date_time.rb

class DateTimeInput < SimpleForm::Inputs::DateTimeInput
  def input(wrapper_options)
    template.content_tag(:div, super)
  end
end
Also added this private method

app/controllers/workouts_controller.rb

def actionname
    @types = Workout.select(:activity).distinct
  end

Test


Add ability to SHOW a specific workout

workouts_controller.rb

class WorkoutsController < ApplicationController
  def index
  end

  def new
    @workout = Workout.new
  end

  def create
    @workout = Workout.new(workout_params)
    if @ workout.save
      redirect_to @workout
    else
      render 'new'
    end
  end

  def show
    @workout = Workout.find(params[:id])
  end

  private
  def workout_params
    params.require(:workout).permit(date time activity location description)
  end

end

===

app/views/workouts/show.html.erb

<h4>Workout on <%= @workout.date_time.strftime("%A, %B %d |  %I:%M %P") %></h4>

<p>Activity: <%= @workout.activity %></p>
<p>Location: <%= @workout.location %></p>
<p><%= @workout.description %></p>

app/views/workouts/new.html.erb

 <p><%= link_to 'Cancel', root_path  %>| <%= link_to 'Back', workout_path %></p>

month id="workout_date_time_1i" day id="workout_date_time_2i" year id="workout_date_time_3i"

hour id="workout_date_time_4i" minute id="workout_date_time_5i"

class = "datetime optional from-control"

Test


Add Ability to EDIT

workouts_controller.rb

class WorkoutsController < ApplicationController
  before_action :find_workout, only: [:show, :edit, :update, :destroy]

  def index
  end

  def new
    @workout = Workout.new
  end

  def create
    @workout = Workout.new(workout_params)
    if @workout.save
      redirect_to @workout
    else
      render :new
    end
  end

  def show
  end

  def edit
  end

  def update
    if @workout.update(workout_params)
      flash[:notice] = "Workout edited."
      redirect_to @workout
    else
      render :edit
      flash[:notice] = "Workout was not edited."
    end
  end

  private

  def find_workout
    @workout = Workout.find(params[:id])
  end

  def workout_params
    params.require(:workout).permit(:date_time, :activity, :location, :description)
  end

end

===

workouts/edit.html

<h1>Edit your Workout</h1>
<%= render 'form' %>
<p><%= link_to 'Cancel', root_path %> | <%= link_to 'Back', workout_path %></p>

Test

Add Destroy Workout to Tests

  describe 'DELETE' do
    before do
      post '/workouts', workout: { date_time: workout.date_time,
                                   activity: workout.activity,
                                   location: workout.location,
                                   description: workout.description }
    end

    it "should delete a workout" do
      expect {
        delete "/workouts/#{Workout.last.id}"
      }.to change(workout, :count).by(-1)
      expect(response).to have_http_status(302)
    end
  end

Add Destroy action & view all workouts on the index page

workouts_controller.rb

class WorkoutsController < ApplicationController
  before_action :find_workout, only: [:show, :edit, :update, :destroy]

  def index
    @workouts = Workout.all.order('created_at ASC')
  end

  def new
    @workout = Workout.new
  end

  def create
    @workout = Workout.new(workout_params)
    if @workout.save
      redirect_to @workout
    else
      render :new
    end
  end

  def show
  end

  def edit
  end

  def update
    if @workout.update(workout_params)
      flash[:notice] = "Workout edited."
      redirect_to @workout
    else
      render :edit
      flash[:notice] = "Workout was not edited."
    end
  end

  def destroy
    @workout.destroy
    flash[:notice] = "Workout deleted."
    redirect_to workouts_path
  end

  private

  def find_workout
    @workout = Workout.find(params[:id])
  end

  def workout_params
    params.require(:workout).permit(:date_time, :activity, :location, :description)
  end

end

Add Delete links

app/views/workouts/show.html.erb

<h4>Workout on <%= @workout.date_time.strftime("%A, %B %d |  %I:%M %P") %></h4>

<p>Activity: <%= @workout.activity %></p>
<p>Location: <%= @workout.location %></p>
<p><%= @workout.description %></p>
<p><%= link_to 'EDIT', edit_workout_path %> | <%= link_to 'DELETE', workouts_path %> | <%= link_to 'BACK', workouts_path %></p>

Test

Add Abilty to view all the Workouts on the INDEX Page & REFACTOR

workouts_controller.rb

class WorkoutsController < ApplicationController
  before_action :find_workout, only: [:show, :edit, :update, :destroy]

  def index
    @workouts = Workout.all.order('created_at ASC')
  end

  def new
    @workout = Workout.new
  end

  def create
    @workout = Workout.new(workout_params)
    if @workout.save
      redirect_to @workout
    else
      render :new
    end
  end

  def show
  end

  def edit
  end

  def update
    if @workout.update(workout_params)
      flash[:notice] = "Workout edited."
      redirect_to @workout
    else
      render :edit
      flash[:notice] = "Workout was not edited."
    end
  end

  def destroy
    @workout.destroy
    flash[:notice] = "Workout deleted."
    redirect_to workouts_path
  end

  private

  def find_workout
    @workout = Workout.find(params[:id])
  end

  def workout_params
    params.require(:workout).permit(:date_time, :activity, :location, :description)
  end

end

Test


Create USER Model

$ rails g model User firstname:string lastname:string email:string phone:string birthday:date
$ rake db:migrate


Test


Add DEVISE

https://github.com/plataformatec/devise

Gemfile
gem 'devise', '~> 3.5', '>= 3.5.6'

$ bundle

===

  • $ rails g controller Users

  • $ rails generate devise:install

  • $ rails generate devise MODEL

config/environments/development.rb config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }


Test


Style Guide

https://www.google.com/fonts#QuickUsePlace:quickUse


for later...?

require 'rails_helper'

RSpec.describe Workout, type: :model do
  describe 'Can we construct an instance of class Workout' do
    it 'attempts to create new Workout class' do
      @workout = Workout.new('1', date, time, hike, 'Griffith Park', 'Carousel Hike')
      expect(@workout.id).to eq('1')
      expect(@workout.date).to eq('new workout')
      expect(@workout.time).to eq('new workout introduction')
    end
  end
  describe 'Can we find an Workout' do
    it 'looks up an workout' do
      @workout1 = Workout::WORKOUTS[0]
      expect(Workout.find(@workout1.id)).to eq(@workout1)
    end
  end
end
15.times do
  Workout.create( date: Date.today.strftime("%A, %B %d"),
                  time: Time.zone.now.strftime("%I:%M %P"),
                  activity: FFaker::Sport.name,
                  location: FFaker::AddressUS.neighborhood,
                  description: FFaker::BaconIpsum.sentence
                )
end

Rails Console

http://zetcode.com/db/sqlite/tool/
https://pragmaticstudio.com/blog/2014/3/11/console-shortcuts-tips-tricks

The y method is a handy way to get some pretty YAML output.

y ProductColor.all

http://rors.org/2009/12/20/10-rails-console-tricks.html
https://signalvnoise.com/posts/3176-three-quick-rails-console-tips
http://www.rubyinside.com/21-ruby-tricks-902.html
http://www.giantflyingsaucer.com/blog/?p=1891
http://slash7.com/2006/12/21/secrets-of-the-rails-console-ninjas/
http://railsonedge.blogspot.com/2008/05/intro-to-rails-console.html

http://guides.rubyonrails.org/command_line.html
rake about

rails console --sandbox


Time Ordinals

active_support's ordinalize helper method
http://apidock.com/rails/ActiveSupport/Inflector/ordinalize
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html

ActiveSupport::Inflector
The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept in inflections.rb.

time = Time.new
Fri Oct 03 01:24:48 +0100 2008

time.strftime("%A, %B #{time.day.ordinalize}")

returns => "Fri Oct 3rd"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment