├── log
└── .keep
├── .rspec
├── app
├── mailers
│ └── .keep
├── assets
│ ├── images
│ │ └── .keep
│ ├── stylesheets
│ │ ├── categories.css.scss
│ │ ├── products.css.scss
│ │ └── application.css.scss
│ └── javascripts
│ │ ├── application.js
│ │ ├── categories.js
│ │ └── products.js
├── models
│ ├── concerns
│ │ └── .keep
│ ├── category.rb
│ ├── review.rb
│ ├── product.rb
│ └── user.rb
├── controllers
│ ├── concerns
│ │ └── .keep
│ ├── application_controller.rb
│ ├── reviews_controller.rb
│ ├── categories_controller.rb
│ └── products_controller.rb
├── helpers
│ ├── categories_helper.rb
│ ├── products_helper.rb
│ └── application_helper.rb
├── views
│ ├── reviews
│ │ ├── _review.html.haml
│ │ └── _form.html.haml
│ ├── products
│ │ ├── new.html.haml
│ │ ├── edit.html.haml
│ │ ├── show.html.haml
│ │ ├── index.html.haml
│ │ └── _form.html.haml
│ ├── categories
│ │ ├── new.html.haml
│ │ ├── edit.html.haml
│ │ ├── show.html.haml
│ │ ├── _form.html.haml
│ │ └── index.html.haml
│ ├── devise
│ │ ├── mailer
│ │ │ ├── confirmation_instructions.html.haml
│ │ │ ├── unlock_instructions.html.haml
│ │ │ └── reset_password_instructions.html.haml
│ │ ├── passwords
│ │ │ ├── new.html.haml
│ │ │ └── edit.html.haml
│ │ ├── sessions
│ │ │ └── new.html.haml
│ │ ├── unlocks
│ │ │ └── new.html.haml
│ │ ├── registrations
│ │ │ ├── new.html.haml
│ │ │ └── edit.html.haml
│ │ ├── confirmations
│ │ │ └── new.html.haml
│ │ └── shared
│ │ │ └── _links.haml
│ └── layouts
│ │ └── application.haml
└── decorators
│ ├── review_decorator.rb
│ ├── category_decorator.rb
│ └── product_decorator.rb
├── lib
├── assets
│ └── .keep
├── tasks
│ └── .keep
└── templates
│ └── haml
│ └── scaffold
│ └── _form.html.haml
├── public
├── favicon.ico
├── robots.txt
├── 500.html
├── 422.html
└── 404.html
├── .ruby-version
├── vendor
└── assets
│ ├── javascripts
│ └── .keep
│ └── stylesheets
│ └── .keep
├── spec
├── decorators
│ ├── product_decorator_spec.rb
│ ├── category_decorator_spec.rb
│ └── review_decorator_spec.rb
├── models
│ ├── category_spec.rb
│ ├── user_spec.rb
│ ├── review_spec.rb
│ └── product_spec.rb
├── factories
│ ├── categories.rb
│ ├── products.rb
│ ├── reviews.rb
│ └── users.rb
├── spec_helper.rb
└── controllers
│ ├── categories_controller_spec.rb
│ └── products_controller_spec.rb
├── bin
├── rake
├── bundle
└── rails
├── config
├── database.yml.travis
├── initializers
│ ├── cookies_serializer.rb
│ ├── session_store.rb
│ ├── secret_token.rb
│ ├── filter_parameter_logging.rb
│ ├── mime_types.rb
│ ├── backtrace_silencers.rb
│ ├── wrap_parameters.rb
│ ├── inflections.rb
│ ├── simple_form_bootstrap.rb
│ ├── simple_form.rb
│ └── devise.rb
├── environment.rb
├── boot.rb
├── secrets.yml.sample
├── routes.rb
├── config.yml
├── preinitializer.rb
├── database.yml.sample
├── locales
│ ├── en.yml
│ ├── simple_form.en.yml
│ └── devise.en.yml
├── application.rb
└── environments
│ ├── development.rb
│ ├── test.rb
│ └── production.rb
├── config.ru
├── db
├── migrate
│ ├── 20140606071025_add_user_ref_to_review.rb
│ ├── 20140606091435_add_user_ref_to_product.rb
│ ├── 20140605204902_add_category_ref_to_product.rb
│ ├── 20140605201457_create_categories.rb
│ ├── 20140605201633_create_products.rb
│ ├── 20140605225158_create_reviews.rb
│ └── 20140605201000_devise_create_users.rb
├── seeds.rb
└── schema.rb
├── Rakefile
├── .travis.yml
├── .gitignore
├── Gemfile
├── code_of_conduct.md
├── README.md
└── Gemfile.lock
/log/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.rspec:
--------------------------------------------------------------------------------
1 | --color
2 |
--------------------------------------------------------------------------------
/app/mailers/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/assets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/lib/tasks/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.ruby-version:
--------------------------------------------------------------------------------
1 | 2.1.5
2 |
--------------------------------------------------------------------------------
/app/assets/images/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/models/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/controllers/concerns/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/javascripts/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/vendor/assets/stylesheets/.keep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/categories.css.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/products.css.scss:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/app/assets/stylesheets/application.css.scss:
--------------------------------------------------------------------------------
1 | @import "bootstrap";
2 |
--------------------------------------------------------------------------------
/app/helpers/categories_helper.rb:
--------------------------------------------------------------------------------
1 | module CategoriesHelper
2 | end
3 |
--------------------------------------------------------------------------------
/app/helpers/products_helper.rb:
--------------------------------------------------------------------------------
1 | module ProductsHelper
2 | end
3 |
--------------------------------------------------------------------------------
/app/helpers/application_helper.rb:
--------------------------------------------------------------------------------
1 | module ApplicationHelper
2 | end
3 |
--------------------------------------------------------------------------------
/app/models/category.rb:
--------------------------------------------------------------------------------
1 | class Category < ActiveRecord::Base
2 | has_many :products
3 | end
4 |
--------------------------------------------------------------------------------
/app/assets/javascripts/application.js:
--------------------------------------------------------------------------------
1 | //= require jquery
2 | //= require jquery_ujs
3 | //= require_tree .
4 |
--------------------------------------------------------------------------------
/spec/decorators/product_decorator_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe ProductDecorator do
4 | end
5 |
--------------------------------------------------------------------------------
/app/models/review.rb:
--------------------------------------------------------------------------------
1 | class Review < ActiveRecord::Base
2 | belongs_to :product
3 | belongs_to :user
4 | end
5 |
--------------------------------------------------------------------------------
/app/views/reviews/_review.html.haml:
--------------------------------------------------------------------------------
1 | %p= review.content
2 | %p
3 | %b= review.rating
4 | %em= review.author
5 |
--------------------------------------------------------------------------------
/bin/rake:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | require_relative '../config/boot'
3 | require 'rake'
4 | Rake.application.run
5 |
--------------------------------------------------------------------------------
/config/database.yml.travis:
--------------------------------------------------------------------------------
1 | test:
2 | adapter: postgresql
3 | database: travis_ci_test
4 | username: postgres
5 |
--------------------------------------------------------------------------------
/spec/decorators/category_decorator_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe CategoryDecorator do
4 | end
5 |
--------------------------------------------------------------------------------
/app/views/products/new.html.haml:
--------------------------------------------------------------------------------
1 | %h1 New product
2 |
3 | = render 'form'
4 |
5 | = link_to 'Back', category_products_path
6 |
--------------------------------------------------------------------------------
/app/models/product.rb:
--------------------------------------------------------------------------------
1 | class Product < ActiveRecord::Base
2 | belongs_to :category
3 | belongs_to :user
4 | has_many :reviews
5 | end
6 |
--------------------------------------------------------------------------------
/spec/models/category_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe Category do
4 | it { should validate_uniqueness_of(:name) }
5 | end
6 |
--------------------------------------------------------------------------------
/app/decorators/review_decorator.rb:
--------------------------------------------------------------------------------
1 | class ReviewDecorator < Draper::Decorator
2 | delegate_all
3 |
4 | def author
5 | end
6 |
7 | end
8 |
--------------------------------------------------------------------------------
/app/views/categories/new.html.haml:
--------------------------------------------------------------------------------
1 | %h1 New category
2 |
3 | = render 'form'
4 |
5 | = link_to 'Back', categories_path, class: 'btn btn-primary'
6 |
--------------------------------------------------------------------------------
/bin/bundle:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3 | load Gem.bin_path('bundler', 'bundle')
4 |
--------------------------------------------------------------------------------
/bin/rails:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ruby
2 | APP_PATH = File.expand_path('../../config/application', __FILE__)
3 | require_relative '../config/boot'
4 | require 'rails/commands'
5 |
--------------------------------------------------------------------------------
/config/initializers/cookies_serializer.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.action_dispatch.cookies_serializer = :json
--------------------------------------------------------------------------------
/config.ru:
--------------------------------------------------------------------------------
1 | # This file is used by Rack-based servers to start the application.
2 |
3 | require ::File.expand_path('../config/environment', __FILE__)
4 | run Rails.application
5 |
--------------------------------------------------------------------------------
/db/migrate/20140606071025_add_user_ref_to_review.rb:
--------------------------------------------------------------------------------
1 | class AddUserRefToReview < ActiveRecord::Migration
2 | def change
3 | add_reference(:reviews, :user)
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/db/migrate/20140606091435_add_user_ref_to_product.rb:
--------------------------------------------------------------------------------
1 | class AddUserRefToProduct < ActiveRecord::Migration
2 | def change
3 | add_reference(:products, :user)
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/app/assets/javascripts/categories.js:
--------------------------------------------------------------------------------
1 | // Place all the behaviors and hooks related to the matching controller here.
2 | // All this logic will automatically be available in application.js.
3 |
--------------------------------------------------------------------------------
/app/assets/javascripts/products.js:
--------------------------------------------------------------------------------
1 | // Place all the behaviors and hooks related to the matching controller here.
2 | // All this logic will automatically be available in application.js.
3 |
--------------------------------------------------------------------------------
/app/views/categories/edit.html.haml:
--------------------------------------------------------------------------------
1 | %h1 Editing category
2 |
3 | = render 'form'
4 |
5 | = link_to 'Show', category
6 | \|
7 | = link_to 'Back', categories_path, class: 'btn btn-primary'
8 |
--------------------------------------------------------------------------------
/config/environment.rb:
--------------------------------------------------------------------------------
1 | # Load the Rails application.
2 | require File.expand_path('../application', __FILE__)
3 |
4 | # Initialize the Rails application.
5 | Rails.application.initialize!
6 |
--------------------------------------------------------------------------------
/config/initializers/session_store.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | Rails.application.config.session_store :cookie_store, key: '_workshops_session'
4 |
--------------------------------------------------------------------------------
/db/migrate/20140605204902_add_category_ref_to_product.rb:
--------------------------------------------------------------------------------
1 | class AddCategoryRefToProduct < ActiveRecord::Migration
2 | def change
3 | add_reference :products, :category
4 | end
5 | end
6 |
--------------------------------------------------------------------------------
/app/views/products/edit.html.haml:
--------------------------------------------------------------------------------
1 | %h1 Editing product
2 |
3 | = render 'form'
4 |
5 | = link_to 'Show', category_product_path(category, product)
6 | \|
7 | = link_to 'Back', category_path(category)
8 |
--------------------------------------------------------------------------------
/config/boot.rb:
--------------------------------------------------------------------------------
1 | # Set up gems listed in the Gemfile.
2 | ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
3 |
4 | require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
5 |
--------------------------------------------------------------------------------
/spec/factories/categories.rb:
--------------------------------------------------------------------------------
1 | # Read about factories at https://github.com/thoughtbot/factory_girl
2 |
3 | FactoryGirl.define do
4 | factory :category do
5 | name "MyString"
6 | end
7 | end
8 |
--------------------------------------------------------------------------------
/spec/factories/products.rb:
--------------------------------------------------------------------------------
1 | FactoryGirl.define do
2 | factory :product do
3 | title "MyString"
4 | description "MyText"
5 | price 1.5
6 | user
7 | category
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/config/initializers/secret_token.rb:
--------------------------------------------------------------------------------
1 | Workshops::Application.config.secret_key_base = "d060e2d61a6ae06cdb5f21a1db7b9a6661e118dab884227d4cf7d7b55a84023d43de964381b0bad755ac6bc81de779f0d15f12498c219fc992b2c4c103c7089b"
2 |
--------------------------------------------------------------------------------
/config/secrets.yml.sample:
--------------------------------------------------------------------------------
1 | development:
2 | secret_key_base: SAMPLE_SECRET_DEV
3 |
4 | test:
5 | secret_key_base: SAMPLE_SECRET_TEST
6 |
7 | production:
8 | secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
9 |
--------------------------------------------------------------------------------
/spec/factories/reviews.rb:
--------------------------------------------------------------------------------
1 | # Read about factories at https://github.com/thoughtbot/factory_girl
2 |
3 | FactoryGirl.define do
4 | factory :review do
5 | content "MyText"
6 | rating 1
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/config/routes.rb:
--------------------------------------------------------------------------------
1 | Rails.application.routes.draw do
2 | resources :categories do
3 | resources :products do
4 | resources :reviews
5 | end
6 | end
7 |
8 | root 'categories#index'
9 | end
10 |
--------------------------------------------------------------------------------
/config/config.yml:
--------------------------------------------------------------------------------
1 | defaults: &defaults
2 | workshops_name: 'Netguru Bialystok Workshops 2015'
3 |
4 | development:
5 | <<: *defaults
6 |
7 | test:
8 | <<: *defaults
9 |
10 | production:
11 | <<: *defaults
12 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 | #
3 | # To ban all spiders from the entire site uncomment the next two lines:
4 | # User-agent: *
5 | # Disallow: /
6 |
--------------------------------------------------------------------------------
/config/preinitializer.rb:
--------------------------------------------------------------------------------
1 | require 'active_support/core_ext'
2 | require 'konf'
3 |
4 | pub_config = (YAML.load(ERB.new(File.read(File.expand_path('../config.yml', __FILE__))).result)[Rails.env]) || {}
5 | AppConfig = Konf.new(pub_config)
6 |
--------------------------------------------------------------------------------
/app/views/devise/mailer/confirmation_instructions.html.haml:
--------------------------------------------------------------------------------
1 | %p
2 | Welcome #{@email}!
3 | %p You can confirm your account email through the link below:
4 | %p= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token)
5 |
--------------------------------------------------------------------------------
/db/migrate/20140605201457_create_categories.rb:
--------------------------------------------------------------------------------
1 | class CreateCategories < ActiveRecord::Migration
2 | def change
3 | create_table :categories do |t|
4 | t.string :name
5 |
6 | t.timestamps
7 | end
8 | end
9 | end
10 |
--------------------------------------------------------------------------------
/app/controllers/application_controller.rb:
--------------------------------------------------------------------------------
1 | class ApplicationController < ActionController::Base
2 |
3 | decent_configuration do
4 | strategy DecentExposure::StrongParametersStrategy
5 | end
6 |
7 | protect_from_forgery with: :exception
8 | end
9 |
--------------------------------------------------------------------------------
/config/initializers/filter_parameter_logging.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Configure sensitive parameters which will be filtered from the log file.
4 | Rails.application.config.filter_parameters += [:password]
5 |
--------------------------------------------------------------------------------
/config/initializers/mime_types.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new mime types for use in respond_to blocks:
4 | # Mime::Type.register "text/richtext", :rtf
5 | # Mime::Type.register_alias "text/html", :iphone
6 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # Add your own tasks in files placed in lib/tasks ending in .rake,
2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
3 |
4 | require File.expand_path('../config/application', __FILE__)
5 |
6 | Rails.application.load_tasks
7 |
--------------------------------------------------------------------------------
/spec/models/user_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe User do
4 | it { should validate_presence_of :firstname }
5 | it { should validate_presence_of :lastname }
6 |
7 | it "by default isn't admin" do
8 | expect(User.new).to_not be_admin
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/spec/factories/users.rb:
--------------------------------------------------------------------------------
1 | # Read about factories at https://github.com/thoughtbot/factory_girl
2 |
3 | FactoryGirl.define do
4 | factory :user do
5 | firstname 'John'
6 | lastname 'Doe'
7 | email { Faker::Internet.email }
8 | password 'password123'
9 | end
10 | end
11 |
--------------------------------------------------------------------------------
/db/migrate/20140605201633_create_products.rb:
--------------------------------------------------------------------------------
1 | class CreateProducts < ActiveRecord::Migration
2 | def change
3 | create_table :products do |t|
4 | t.string :title
5 | t.text :description
6 | t.float :price
7 |
8 | t.timestamps
9 | end
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/db/migrate/20140605225158_create_reviews.rb:
--------------------------------------------------------------------------------
1 | class CreateReviews < ActiveRecord::Migration
2 | def change
3 | create_table :reviews do |t|
4 | t.text :content
5 | t.integer :rating
6 |
7 | t.timestamps
8 | end
9 | add_reference(:reviews, :product)
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/app/views/devise/mailer/unlock_instructions.html.haml:
--------------------------------------------------------------------------------
1 | %p
2 | Hello #{@resource.email}!
3 | %p Your account has been locked due to an excessive number of unsuccessful sign in attempts.
4 | %p Click the link below to unlock your account:
5 | %p= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token)
6 |
--------------------------------------------------------------------------------
/spec/models/review_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe Review do
4 | describe 'validations' do
5 | it { should validate_presence_of :content }
6 | it { should validate_presence_of :rating }
7 | it { should validate_presence_of :user_id }
8 | it { should belong_to :user }
9 |
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/config/database.yml.sample:
--------------------------------------------------------------------------------
1 | connection: &connection
2 | adapter: postgresql
3 | encoding: unicode
4 | host: localhost
5 | pool: 5
6 | username: workshops
7 | password:
8 |
9 | development:
10 | <<: *connection
11 | database: workshops_development
12 |
13 | test: &test
14 | <<: *connection
15 | database: workshops_test
16 |
--------------------------------------------------------------------------------
/lib/templates/haml/scaffold/_form.html.haml:
--------------------------------------------------------------------------------
1 | = simple_form_for(@<%= singular_table_name %>) do |f|
2 | = f.error_notification
3 |
4 | .form-inputs
5 | <%- attributes.each do |attribute| -%>
6 | = f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %>
7 | <%- end -%>
8 |
9 | .form-actions
10 | = f.button :submit
11 |
--------------------------------------------------------------------------------
/app/models/user.rb:
--------------------------------------------------------------------------------
1 | class User < ActiveRecord::Base
2 | # Include default devise modules. Others available are:
3 | # :confirmable, :lockable, :timeoutable and :omniauthable
4 | devise :database_authenticatable, :registerable,
5 | :recoverable, :rememberable, :trackable, :validatable
6 |
7 | has_many :reviews
8 | has_many :products
9 | end
10 |
--------------------------------------------------------------------------------
/db/seeds.rb:
--------------------------------------------------------------------------------
1 | # This file should contain all the record creation needed to seed the database with its default values.
2 | # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
3 | #
4 | # Examples:
5 | #
6 | # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
7 | # Mayor.create(name: 'Emanuel', city: cities.first)
8 |
--------------------------------------------------------------------------------
/app/views/categories/show.html.haml:
--------------------------------------------------------------------------------
1 | %p#notice= notice
2 |
3 | %p
4 | %b Name:
5 | = category.name
6 |
7 | %p
8 | - category.products.each do |product|
9 | = product.title
10 |
11 | %p
12 | %h3 New product
13 | = render 'products/form'
14 |
15 | = link_to 'Edit', edit_category_path(category)
16 | \|
17 | = link_to 'Back', categories_path, class: 'btn btn-primary'
18 |
--------------------------------------------------------------------------------
/app/views/devise/passwords/new.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Forgot your password?
2 | = simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f|
3 | = f.error_notification
4 | .form-inputs
5 | = f.input :email, required: true, autofocus: true
6 | .form-actions
7 | = f.button :submit, "Send me reset password instructions"
8 | = render "devise/shared/links"
9 |
--------------------------------------------------------------------------------
/spec/decorators/review_decorator_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe ReviewDecorator do
4 |
5 | let(:user) { build(:user, firstname: 'John', lastname: 'Doe') }
6 | let(:review) { described_class.new(build(:review, user: user)) }
7 |
8 | describe '#author' do
9 | it 'displays review author fullname' do
10 | expect(review.author).to eq 'John Doe'
11 | end
12 | end
13 | end
14 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: ruby
2 | rvm:
3 | - 2.1.5
4 | deploy:
5 | provider: heroku
6 | api_key:
7 | secure: <%= ENV['API_SECRET'] %>
8 | run:
9 | - 'rake db:migrate'
10 | app: <%= ENV['HEROKU_APP_NAME'] %>
11 | on:
12 | repo: netguru-training/workshops
13 | before_script:
14 | - cp config/database.yml.travis config/database.yml
15 | - psql -c 'create database travis_ci_test;' -U postgres
16 |
--------------------------------------------------------------------------------
/app/views/devise/mailer/reset_password_instructions.html.haml:
--------------------------------------------------------------------------------
1 | %p
2 | Hello #{@resource.email}!
3 | %p Someone has requested a link to change your password. You can do this through the link below.
4 | %p= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token)
5 | %p If you didn't request this, please ignore this email.
6 | %p Your password won't change until you access the link above and create a new one.
7 |
--------------------------------------------------------------------------------
/app/views/devise/sessions/new.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Sign in
2 | = simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f|
3 | .form-inputs
4 | = f.input :email, required: false, autofocus: true
5 | = f.input :password, required: false
6 | = f.input :remember_me, as: :boolean if devise_mapping.rememberable?
7 | .form-actions
8 | = f.button :submit, "Sign in"
9 | = render "devise/shared/links"
10 |
--------------------------------------------------------------------------------
/app/views/devise/unlocks/new.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Resend unlock instructions
2 | = simple_form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f|
3 | = f.error_notification
4 | = f.full_error :unlock_token
5 | .form-inputs
6 | = f.input :email, required: true, autofocus: true
7 | .form-actions
8 | = f.button :submit, "Resend unlock instructions"
9 | = render "devise/shared/links"
10 |
--------------------------------------------------------------------------------
/app/decorators/category_decorator.rb:
--------------------------------------------------------------------------------
1 | class CategoryDecorator < Draper::Decorator
2 | delegate_all
3 |
4 | # Define presentation-specific methods here. Helpers are accessed through
5 | # `helpers` (aka `h`). You can override attributes, for example:
6 | #
7 | # def created_at
8 | # helpers.content_tag :span, class: 'time' do
9 | # object.created_at.strftime("%a %m/%d/%y")
10 | # end
11 | # end
12 |
13 | end
14 |
--------------------------------------------------------------------------------
/app/decorators/product_decorator.rb:
--------------------------------------------------------------------------------
1 | class ProductDecorator < Draper::Decorator
2 | delegate_all
3 |
4 | # Define presentation-specific methods here. Helpers are accessed through
5 | # `helpers` (aka `h`). You can override attributes, for example:
6 | #
7 | # def created_at
8 | # helpers.content_tag :span, class: 'time' do
9 | # object.created_at.strftime("%a %m/%d/%y")
10 | # end
11 | # end
12 |
13 | end
14 |
--------------------------------------------------------------------------------
/app/views/devise/registrations/new.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Sign up
2 | = simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f|
3 | = f.error_notification
4 | .form-inputs
5 | = f.input :email, required: true, autofocus: true
6 | = f.input :password, required: true
7 | = f.input :password_confirmation, required: true
8 | .form-actions
9 | = f.button :submit, "Sign up"
10 | = render "devise/shared/links"
11 |
--------------------------------------------------------------------------------
/config/initializers/backtrace_silencers.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
5 |
6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
7 | # Rails.backtrace_cleaner.remove_silencers!
8 |
--------------------------------------------------------------------------------
/app/views/devise/confirmations/new.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Resend confirmation instructions
2 | = simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f|
3 | = f.error_notification
4 | = f.full_error :confirmation_token
5 | .form-inputs
6 | = f.input :email, required: true, autofocus: true
7 | .form-actions
8 | = f.button :submit, "Resend confirmation instructions"
9 | = render "devise/shared/links"
10 |
--------------------------------------------------------------------------------
/app/views/categories/_form.html.haml:
--------------------------------------------------------------------------------
1 | = form_for category do |f|
2 | - if category.errors.any?
3 | #error_explanation
4 | %h2= "#{pluralize(category.errors.count, "error")} prohibited this category from being saved:"
5 | %ul
6 | - category.errors.full_messages.each do |msg|
7 | %li= msg
8 |
9 | .form-group
10 | = f.label :name
11 | = f.text_field :name, class: 'form-control'
12 |
13 | = f.submit 'Save', class: 'btn btn-default'
14 |
--------------------------------------------------------------------------------
/app/views/categories/index.html.haml:
--------------------------------------------------------------------------------
1 | %h1 Listing categories
2 |
3 | %table.table
4 | %tr
5 | %th Name
6 | %th
7 | %th
8 | %th
9 |
10 | - categories.each do |category|
11 | %tr
12 | %td= category.name
13 | %td= link_to 'Show', category
14 | %td= link_to 'Edit', edit_category_path(category)
15 | %td= link_to 'Destroy', category, method: :delete, data: { confirm: 'Are you sure?' }
16 |
17 | %br
18 |
19 | = link_to 'New Category', new_category_path
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore bundler config.
2 | /.bundle
3 |
4 | # Ignore all logfiles and tempfiles.
5 | /log/*.log
6 | /tmp
7 |
8 | /coverage
9 |
10 | public/tmp
11 | public/uploads
12 | public/javascripts/translations.js
13 |
14 | config/mongoid.yml
15 | config/secrets.yml
16 | config/database.yml
17 |
18 | .rbenv-gemsets
19 | .rbenv-version
20 | .powenv
21 | .env
22 | .rvmrc
23 | .powrc
24 |
25 | logfile
26 |
27 | local.local.*
28 |
29 | # Ignore application configuration
30 | /config/application.yml
31 |
--------------------------------------------------------------------------------
/app/views/products/show.html.haml:
--------------------------------------------------------------------------------
1 | %p#notice= notice
2 | %p#error= flash[:error]
3 |
4 | %p
5 | %b Title:
6 | = product.title
7 | %p
8 | %b Description:
9 | = product.description
10 | %p
11 | %b Price:
12 | = product.price
13 |
14 | %p
15 | %b Category
16 | = product.category.name
17 |
18 | %h3 Reviews
19 | = render 'reviews/form'
20 |
21 | = render reviews
22 |
23 | = link_to 'Edit', edit_category_product_path(category.id, product.id)
24 | \|
25 | = link_to 'Back', category_products_path, class: 'btn btn-primary'
26 |
--------------------------------------------------------------------------------
/app/views/reviews/_form.html.haml:
--------------------------------------------------------------------------------
1 | = simple_form_for [category, product, review] do |f|
2 | - if review.errors.any?
3 | #error_explanation
4 | %h2= "#{pluralize(review.errors.count, "error")} prohibited this review from being saved:"
5 | %ul
6 | - review.errors.full_messages.each do |msg|
7 | %li= msg
8 | .form-group
9 | = f.label :content
10 | = f.text_area :content, class: 'form-control'
11 | .form-group
12 | = f.input :rating, collection: 1..5, class: 'form-control'
13 |
14 | = f.submit 'Save', class: 'btn btn-default'
15 |
--------------------------------------------------------------------------------
/app/views/devise/passwords/edit.html.haml:
--------------------------------------------------------------------------------
1 | %h2 Change your password
2 | = simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f|
3 | = f.error_notification
4 | = f.input :reset_password_token, as: :hidden
5 | = f.full_error :reset_password_token
6 | .form-inputs
7 | = f.input :password, label: "New password", required: true, autofocus: true
8 | = f.input :password_confirmation, label: "Confirm your new password", required: true
9 | .form-actions
10 | = f.button :submit, "Change my password"
11 | = render "devise/shared/links"
12 |
--------------------------------------------------------------------------------
/config/initializers/wrap_parameters.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # This file contains settings for ActionController::ParamsWrapper which
4 | # is enabled by default.
5 |
6 | # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
7 | ActiveSupport.on_load(:action_controller) do
8 | wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
9 | end
10 |
11 | # To enable root element in JSON for ActiveRecord objects.
12 | # ActiveSupport.on_load(:active_record) do
13 | # self.include_root_in_json = true
14 | # end
15 |
--------------------------------------------------------------------------------
/app/views/products/index.html.haml:
--------------------------------------------------------------------------------
1 | %h1 Listing products
2 |
3 | %table
4 | %tr
5 | %th Title
6 | %th Description
7 | %th Price
8 | %th
9 | %th
10 | %th
11 |
12 | - products.each do |product|
13 | %tr
14 | %td= product.title
15 | %td= product.description
16 | %td= product.price
17 | %td= link_to 'Show', category_product_path(product.category, product)
18 | %td= link_to 'Edit', edit_category_product_path(product.category, product)
19 | %td= link_to 'Destroy', category_product_path(product.category, product), method: :delete, data: { confirm: 'Are you sure?' }
20 |
21 | %br
22 |
--------------------------------------------------------------------------------
/app/views/products/_form.html.haml:
--------------------------------------------------------------------------------
1 | = form_for [category, product] do |f|
2 | - if product.errors.any?
3 | #error_explanation
4 | %h2= "#{pluralize(product.errors.count, "error")} prohibited this product from being saved:"
5 | %ul
6 | - product.errors.full_messages.each do |msg|
7 | %li= msg
8 |
9 | .form-group
10 | = f.label :title
11 | = f.text_field :title, class: 'form-control'
12 | .form-group
13 | = f.label :description
14 | = f.text_area :description, class: 'form-control'
15 | .form-group
16 | = f.label :price
17 | = f.text_field :price, class: 'form-control'
18 |
19 | = f.submit 'Save', class: 'btn btn-default'
20 |
--------------------------------------------------------------------------------
/app/views/layouts/application.haml:
--------------------------------------------------------------------------------
1 | !!!
2 | %html{ lang: 'en' }
3 | %head
4 | %meta{ charset: 'utf-8' }/
5 | %meta{ content: 'IE=Edge,chrome=1', 'http-equiv' => 'X-UA-Compatible' }/
6 | %meta{ content: 'width=device-width, initial-scale=1.0', name: 'viewport' }/
7 | = csrf_meta_tags
8 | = stylesheet_link_tag 'application', media: 'all'
9 | = javascript_include_tag 'application'
10 |
11 | %body
12 | %nav.navbar.navbar-default
13 | .container-fluid
14 | .navbar-header
15 | %span.navbar-brand #{AppConfig.workshops_name}
16 | %p.navbar-text.navbar-right
17 | Links should go here
18 | .container-fluid
19 | .row
20 | .col-lg-12
21 | = yield
22 |
--------------------------------------------------------------------------------
/config/initializers/inflections.rb:
--------------------------------------------------------------------------------
1 | # Be sure to restart your server when you modify this file.
2 |
3 | # Add new inflection rules using the following format. Inflections
4 | # are locale specific, and you may define rules for as many different
5 | # locales as you wish. All of these examples are active by default:
6 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
7 | # inflect.plural /^(ox)$/i, '\1en'
8 | # inflect.singular /^(ox)en/i, '\1'
9 | # inflect.irregular 'person', 'people'
10 | # inflect.uncountable %w( fish sheep )
11 | # end
12 |
13 | # These inflection rules are supported but not enabled by default:
14 | # ActiveSupport::Inflector.inflections(:en) do |inflect|
15 | # inflect.acronym 'RESTful'
16 | # end
17 |
--------------------------------------------------------------------------------
/config/locales/en.yml:
--------------------------------------------------------------------------------
1 | # Files in the config/locales directory are used for internationalization
2 | # and are automatically loaded by Rails. If you want to use locales other
3 | # than English, add the necessary files in this directory.
4 | #
5 | # To use the locales, use `I18n.t`:
6 | #
7 | # I18n.t 'hello'
8 | #
9 | # In views, this is aliased to just `t`:
10 | #
11 | # <%= t('hello') %>
12 | #
13 | # To use a different locale, set it with `I18n.locale`:
14 | #
15 | # I18n.locale = :es
16 | #
17 | # This would use the information in config/locales/es.yml.
18 | #
19 | # To learn more, please read the Rails Internationalization guide
20 | # available at http://guides.rubyonrails.org/i18n.html.
21 |
22 | en:
23 | hello: "Hello world"
24 |
--------------------------------------------------------------------------------
/app/controllers/reviews_controller.rb:
--------------------------------------------------------------------------------
1 | class ReviewsController < ApplicationController
2 |
3 | expose(:review)
4 | expose(:product)
5 |
6 | def edit
7 | end
8 |
9 | def create
10 | self.review = Review.new(review_params)
11 |
12 | if review.save
13 | product.reviews << review
14 | redirect_to category_product_url(product.category, product), notice: 'Review was successfully created.'
15 | else
16 | render action: 'new'
17 | end
18 | end
19 |
20 | def destroy
21 | review.destroy
22 | redirect_to category_product_url(product.category, product), notice: 'Review was successfully destroyed.'
23 | end
24 |
25 | private
26 | def review_params
27 | params.require(:review).permit(:content, :rating)
28 | end
29 | end
30 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | gem 'rails', '4.1.8'
4 |
5 | gem 'pg'
6 | gem 'draper'
7 | gem 'decent_exposure'
8 | gem 'decent_decoration'
9 | gem 'devise'
10 | gem 'simple_form', '~> 3.1.0rc'
11 | gem 'bootstrap-sass', '~> 3.1.0'
12 | gem 'haml-rails'
13 | gem 'sass-rails', github: 'rails/sass-rails'
14 | gem 'coffee-rails'
15 | gem 'uglifier'
16 | gem 'quiet_assets'
17 | gem 'jquery-rails'
18 | gem 'therubyracer', platforms: :ruby
19 | gem 'travis'
20 | gem 'ffaker'
21 | gem 'konf'
22 |
23 | group :development do
24 | gem 'spring'
25 | end
26 |
27 | group :development, :test do
28 | gem 'rspec-rails'
29 | gem 'factory_girl_rails'
30 | gem 'shoulda-matchers'
31 | gem 'pry'
32 | end
33 |
34 | group :test do
35 | gem 'database_cleaner'
36 | end
37 |
38 | ruby '2.1.5'
39 |
--------------------------------------------------------------------------------
/spec/models/product_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe Product do
4 | describe 'validations' do
5 | it { should validate_presence_of :title }
6 | it { should validate_presence_of :description }
7 | it { should validate_presence_of :price }
8 |
9 | describe '#price' do
10 | let(:product) { build(:product, price: 1.234) }
11 |
12 | it 'is limited to two decimal places' do
13 | expect(product).to_not be_valid
14 | end
15 | end
16 |
17 | describe '#average_rating' do
18 | let(:user) { create(:user) }
19 | let(:product) { create(:product) }
20 | let(:review1) { create(:review, rating: 2, user: user) }
21 | let(:review2) { create(:review, rating: 3, user: user) }
22 |
23 | before do
24 | product.reviews << [review1, review2]
25 | end
26 |
27 | it 'calculates average rating' do
28 | expect(product.average_rating).to eq 2.5
29 | end
30 | end
31 | end
32 | end
33 |
--------------------------------------------------------------------------------
/config/locales/simple_form.en.yml:
--------------------------------------------------------------------------------
1 | en:
2 | simple_form:
3 | "yes": 'Yes'
4 | "no": 'No'
5 | required:
6 | text: 'required'
7 | mark: '*'
8 | # You can uncomment the line below if you need to overwrite the whole required html.
9 | # When using html, text and mark won't be used.
10 | # html: '*'
11 | error_notification:
12 | default_message: "Please review the problems below:"
13 | # Examples
14 | # labels:
15 | # defaults:
16 | # password: 'Password'
17 | # user:
18 | # new:
19 | # email: 'E-mail to sign in.'
20 | # edit:
21 | # email: 'E-mail.'
22 | # hints:
23 | # defaults:
24 | # username: 'User name to sign in.'
25 | # password: 'No special characters, please.'
26 | # include_blanks:
27 | # defaults:
28 | # age: 'Rather not say'
29 | # prompts:
30 | # defaults:
31 | # age: 'Select your age'
32 |
--------------------------------------------------------------------------------
/app/views/devise/registrations/edit.html.haml:
--------------------------------------------------------------------------------
1 | %h2
2 | Edit #{resource_name.to_s.humanize}
3 | = simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f|
4 | = f.error_notification
5 | .form-inputs
6 | = f.input :email, required: true, autofocus: true
7 | - if devise_mapping.confirmable? && resource.pending_reconfirmation?
8 | %p
9 | Currently waiting confirmation for: #{resource.unconfirmed_email}
10 | = f.input :password, autocomplete: "off", hint: "leave it blank if you don't want to change it", required: false
11 | = f.input :password_confirmation, required: false
12 | = f.input :current_password, hint: "we need your current password to confirm your changes", required: true
13 | .form-actions
14 | = f.button :submit, "Update"
15 | %h3 Cancel my account
16 | %p
17 | Unhappy? #{link_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete}
18 | = link_to "Back", :back
19 |
--------------------------------------------------------------------------------
/config/application.rb:
--------------------------------------------------------------------------------
1 | require File.expand_path('../boot', __FILE__)
2 |
3 | require 'rails/all'
4 |
5 | require File.expand_path('../preinitializer', __FILE__)
6 |
7 | Bundler.require(*Rails.groups)
8 |
9 | module Workshops
10 | class Application < Rails::Application
11 | # Settings in config/environments/* take precedence over those specified here.
12 | # Application configuration should go into files in config/initializers
13 | # -- all .rb files in that directory are automatically loaded.
14 |
15 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
16 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
17 | # config.time_zone = 'Central Time (US & Canada)'
18 |
19 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
20 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
21 | # config.i18n.default_locale = :de
22 | end
23 | end
24 |
--------------------------------------------------------------------------------
/app/views/devise/shared/_links.haml:
--------------------------------------------------------------------------------
1 | - if controller_name != 'sessions'
2 | = link_to "Sign in", new_session_path(resource_name)
3 | %br/
4 | - if devise_mapping.registerable? && controller_name != 'registrations'
5 | = link_to "Sign up", new_registration_path(resource_name)
6 | %br/
7 | - if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations'
8 | = link_to "Forgot your password?", new_password_path(resource_name)
9 | %br/
10 | - if devise_mapping.confirmable? && controller_name != 'confirmations'
11 | = link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name)
12 | %br/
13 | - if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks'
14 | = link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name)
15 | %br/
16 | - if devise_mapping.omniauthable?
17 | - resource_class.omniauth_providers.each do |provider|
18 | = link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider)
19 | %br/
20 |
--------------------------------------------------------------------------------
/app/controllers/categories_controller.rb:
--------------------------------------------------------------------------------
1 | class CategoriesController < ApplicationController
2 | before_action :authenticate_user!, only: [:new, :edit, :update, :destroy, :create]
3 |
4 | expose(:categories)
5 | expose(:category)
6 | expose(:product) { Product.new }
7 |
8 | def index
9 | end
10 |
11 | def show
12 | end
13 |
14 | def new
15 | end
16 |
17 | def edit
18 | end
19 |
20 | def create
21 | self.category = Category.new(category_params)
22 |
23 | if category.save
24 | redirect_to category, notice: 'Category was successfully created.'
25 | else
26 | render action: 'new'
27 | end
28 | end
29 |
30 | def update
31 | if category.update(category_params)
32 | redirect_to category, notice: 'Category was successfully updated.'
33 | else
34 | render action: 'edit'
35 | end
36 | end
37 |
38 | def destroy
39 | category.destroy
40 | redirect_to categories_url, notice: 'Category was successfully destroyed.'
41 | end
42 |
43 | private
44 | def category_params
45 | params.require(:category).permit(:name)
46 | end
47 | end
48 |
--------------------------------------------------------------------------------
/app/controllers/products_controller.rb:
--------------------------------------------------------------------------------
1 | class ProductsController < ApplicationController
2 | expose(:category)
3 | expose(:products)
4 | expose(:product)
5 | expose(:review) { Review.new }
6 | expose_decorated(:reviews, ancestor: :product)
7 |
8 | def index
9 | end
10 |
11 | def show
12 | end
13 |
14 | def new
15 | end
16 |
17 | def edit
18 | end
19 |
20 | def create
21 | self.product = Product.new(product_params)
22 |
23 | if product.save
24 | category.products << product
25 | redirect_to category_product_url(category, product), notice: 'Product was successfully created.'
26 | else
27 | render action: 'new'
28 | end
29 | end
30 |
31 | def update
32 | if self.product.update(product_params)
33 | redirect_to category_product_url(category, product), notice: 'Product was successfully updated.'
34 | else
35 | render action: 'edit'
36 | end
37 | end
38 |
39 | # DELETE /products/1
40 | def destroy
41 | product.destroy
42 | redirect_to category_url(product.category), notice: 'Product was successfully destroyed.'
43 | end
44 |
45 | private
46 |
47 | def product_params
48 | params.require(:product).permit(:title, :description, :price, :category_id)
49 | end
50 | end
51 |
--------------------------------------------------------------------------------
/db/migrate/20140605201000_devise_create_users.rb:
--------------------------------------------------------------------------------
1 | class DeviseCreateUsers < ActiveRecord::Migration
2 | def change
3 | create_table(:users) do |t|
4 | ## Database authenticatable
5 | t.string :email, null: false, default: ""
6 | t.string :encrypted_password, null: false, default: ""
7 |
8 | ## Recoverable
9 | t.string :reset_password_token
10 | t.datetime :reset_password_sent_at
11 |
12 | ## Rememberable
13 | t.datetime :remember_created_at
14 |
15 | ## Trackable
16 | t.integer :sign_in_count, default: 0, null: false
17 | t.datetime :current_sign_in_at
18 | t.datetime :last_sign_in_at
19 | t.string :current_sign_in_ip
20 | t.string :last_sign_in_ip
21 |
22 | ## Confirmable
23 | # t.string :confirmation_token
24 | # t.datetime :confirmed_at
25 | # t.datetime :confirmation_sent_at
26 | # t.string :unconfirmed_email # Only if using reconfirmable
27 |
28 | ## Lockable
29 | # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
30 | # t.string :unlock_token # Only if unlock strategy is :email or :both
31 | # t.datetime :locked_at
32 |
33 |
34 | t.timestamps
35 | end
36 |
37 | add_index :users, :email, unique: true
38 | add_index :users, :reset_password_token, unique: true
39 | # add_index :users, :confirmation_token, unique: true
40 | # add_index :users, :unlock_token, unique: true
41 | end
42 | end
43 |
--------------------------------------------------------------------------------
/config/environments/development.rb:
--------------------------------------------------------------------------------
1 | Workshops::Application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # In the development environment your application's code is reloaded on
5 | # every request. This slows down response time but is perfect for development
6 | # since you don't have to restart the web server when you make code changes.
7 | config.cache_classes = false
8 |
9 | # Do not eager load code on boot.
10 | config.eager_load = false
11 |
12 | # Show full error reports and disable caching.
13 | config.consider_all_requests_local = true
14 | config.action_controller.perform_caching = false
15 |
16 | # Don't care if the mailer can't send.
17 | config.action_mailer.raise_delivery_errors = false
18 |
19 | # Print deprecation notices to the Rails logger.
20 | config.active_support.deprecation = :log
21 |
22 | # Raise an error on page load if there are pending migrations.
23 | config.active_record.migration_error = :page_load
24 |
25 | # Debug mode disables concatenation and preprocessing of assets.
26 | # This option may cause significant delays in view rendering with a large
27 | # number of complex assets.
28 | config.assets.debug = true
29 |
30 | # Adds additional error checking when serving assets at runtime.
31 | # Checks for improperly declared sprockets dependencies.
32 | # Raises helpful error messages.
33 | config.assets.raise_runtime_errors = true
34 |
35 | # Raises error for missing translations
36 | # config.action_view.raise_on_missing_translations = true
37 | end
38 |
--------------------------------------------------------------------------------
/spec/spec_helper.rb:
--------------------------------------------------------------------------------
1 | # This file is copied to spec/ when you run 'rails generate rspec:install'
2 | ENV["RAILS_ENV"] ||= 'test'
3 | require File.expand_path("../../config/environment", __FILE__)
4 | require 'rspec/rails'
5 | require 'rspec/autorun'
6 | require 'database_cleaner'
7 |
8 | # Requires supporting ruby files with custom matchers and macros, etc,
9 | # in spec/support/ and its subdirectories.
10 | Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
11 |
12 | RSpec.configure do |config|
13 | config.include Devise::TestHelpers, type: :controller
14 | config.include FactoryGirl::Syntax::Methods
15 | # ## Mock Framework
16 | #
17 | # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
18 | #
19 | # config.mock_with :mocha
20 | # config.mock_with :flexmock
21 | # config.mock_with :rr
22 |
23 | # If true, the base class of anonymous controllers will be inferred
24 | # automatically. This will be the default behavior in future versions of
25 | # rspec-rails.
26 | config.infer_base_class_for_anonymous_controllers = false
27 | config.raise_errors_for_deprecations!
28 |
29 | config.before(:suite) do
30 | DatabaseCleaner.strategy = :truncation
31 | end
32 |
33 | config.before(:each) do
34 | DatabaseCleaner.clean
35 | end
36 |
37 | # Run specs in random order to surface order dependencies. If you find an
38 | # order dependency and want to debug it, you can fix the order by providing
39 | # the seed, which is printed after each run.
40 | # --seed 1234
41 | config.order = "random"
42 | config.infer_spec_type_from_file_location!
43 | end
44 |
--------------------------------------------------------------------------------
/public/500.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | We're sorry, but something went wrong (500)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
We're sorry, but something went wrong.
62 |
63 |
If you are the application owner check the logs for more information.
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/config/environments/test.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # The test environment is used exclusively to run your application's
5 | # test suite. You never need to work with it otherwise. Remember that
6 | # your test database is "scratch space" for the test suite and is wiped
7 | # and recreated between test runs. Don't rely on the data there!
8 | config.cache_classes = true
9 |
10 | # Do not eager load code on boot. This avoids loading your whole application
11 | # just for the purpose of running a single test. If you are using a tool that
12 | # preloads Rails for running tests, you may have to set it to true.
13 | config.eager_load = false
14 |
15 | # Configure static asset server for tests with Cache-Control for performance.
16 | config.serve_static_assets = true
17 | config.static_cache_control = 'public, max-age=3600'
18 |
19 | # Show full error reports and disable caching.
20 | config.consider_all_requests_local = true
21 | config.action_controller.perform_caching = false
22 |
23 | # Raise exceptions instead of rendering exception templates.
24 | config.action_dispatch.show_exceptions = false
25 |
26 | # Disable request forgery protection in test environment.
27 | config.action_controller.allow_forgery_protection = false
28 |
29 | # Tell Action Mailer not to deliver emails to the real world.
30 | # The :test delivery method accumulates sent emails in the
31 | # ActionMailer::Base.deliveries array.
32 | config.action_mailer.delivery_method = :test
33 |
34 | # Print deprecation notices to the stderr.
35 | config.active_support.deprecation = :stderr
36 |
37 | # Raises error for missing translations
38 | # config.action_view.raise_on_missing_translations = true
39 | end
40 |
--------------------------------------------------------------------------------
/public/422.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The change you wanted was rejected (422)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The change you wanted was rejected.
62 |
Maybe you tried to change something you didn't have access to.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/public/404.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | The page you were looking for doesn't exist (404)
5 |
6 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
The page you were looking for doesn't exist.
62 |
You may have mistyped the address or the page may have moved.
63 |
64 |
If you are the application owner check the logs for more information.
65 |
66 |
67 |
68 |
--------------------------------------------------------------------------------
/code_of_conduct.md:
--------------------------------------------------------------------------------
1 | # Workshops Code of Conduct
2 |
3 | All attendees, mentors and volunteers at our workshops are required to agree with the following code of conduct. Organisers will enforce this code throughout the event. We are expecting cooperation from all participants to help ensuring a safe environment for everybody.
4 |
5 | *tl;dr: Don’t be a Jerk*
6 |
7 | ### YOU NEED HELP?
8 |
9 | Send an email to workshops@netguru.co.
10 |
11 | ### THE QUICK VERSION
12 |
13 | Our event is dedicated to providing a harassment-free workshop experience for everyone, regardless of gender, sexual orientation, disability, physical appearance, body size, race, or religion. We do not tolerate harassment of events participants in any form. Sexual language and imagery is not appropriate for any events venue, including talks, workshops, parties, Twitter and other online media. Workshop participants violating these rules may be sanctioned or expelled from the event at the discretion of the event organisers.
14 |
15 | ### THE LESS QUICK VERSION
16 |
17 | Harassment includes offensive verbal comments related to gender, sexual orientation, disability, physical appearance, body size, race, religion, sexual images in public spaces, deliberate intimidation, stalking, following, harassing photography or recording, sustained disruption of talks or other events, inappropriate physical contact, and unwelcome sexual attention.
18 |
19 | Participants asked to stop any harassing behavior are expected to comply immediately.
20 |
21 | If a participant engages in harassing behavior, the event organizers may take any action they deem appropriate, including warning the offender or expulsion from the event.
22 |
23 | If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact a member of workshop staff immediately.
24 |
25 | Event staff will be happy to help participants contact hotel/venue security or local law enforcement, provide escorts, or otherwise assist those experiencing harassment to feel safe for the duration of the event. We value your attendance.
26 |
27 | We expect participants to follow these rules at workshop venues and workshops-related social events.
28 |
29 | Adapted from [eurucamp](http://2014.eurucamp.org/policies/).
30 |
--------------------------------------------------------------------------------
/db/schema.rb:
--------------------------------------------------------------------------------
1 | # encoding: UTF-8
2 | # This file is auto-generated from the current state of the database. Instead
3 | # of editing this file, please use the migrations feature of Active Record to
4 | # incrementally modify your database, and then regenerate this schema definition.
5 | #
6 | # Note that this schema.rb definition is the authoritative source for your
7 | # database schema. If you need to create the application database on another
8 | # system, you should be using db:schema:load, not running all the migrations
9 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations
10 | # you'll amass, the slower it'll run and the greater likelihood for issues).
11 | #
12 | # It's strongly recommended that you check this file into your version control system.
13 |
14 | ActiveRecord::Schema.define(version: 20140606091435) do
15 |
16 | # These are extensions that must be enabled in order to support this database
17 | enable_extension "plpgsql"
18 |
19 | create_table "categories", force: true do |t|
20 | t.string "name"
21 | t.datetime "created_at"
22 | t.datetime "updated_at"
23 | end
24 |
25 | create_table "products", force: true do |t|
26 | t.string "title"
27 | t.text "description"
28 | t.float "price"
29 | t.datetime "created_at"
30 | t.datetime "updated_at"
31 | t.integer "category_id"
32 | t.integer "user_id"
33 | end
34 |
35 | create_table "reviews", force: true do |t|
36 | t.text "content"
37 | t.integer "rating"
38 | t.datetime "created_at"
39 | t.datetime "updated_at"
40 | t.integer "product_id"
41 | t.integer "user_id"
42 | end
43 |
44 | create_table "users", force: true do |t|
45 | t.string "email", default: "", null: false
46 | t.string "encrypted_password", default: "", null: false
47 | t.string "reset_password_token"
48 | t.datetime "reset_password_sent_at"
49 | t.datetime "remember_created_at"
50 | t.integer "sign_in_count", default: 0, null: false
51 | t.datetime "current_sign_in_at"
52 | t.datetime "last_sign_in_at"
53 | t.string "current_sign_in_ip"
54 | t.string "last_sign_in_ip"
55 | t.datetime "created_at"
56 | t.datetime "updated_at"
57 | end
58 |
59 | add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
60 | add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
61 |
62 | end
63 |
--------------------------------------------------------------------------------
/config/environments/production.rb:
--------------------------------------------------------------------------------
1 | Rails.application.configure do
2 | # Settings specified here will take precedence over those in config/application.rb.
3 |
4 | # Code is not reloaded between requests.
5 | config.cache_classes = true
6 |
7 | # Eager load code on boot. This eager loads most of Rails and
8 | # your application in memory, allowing both threaded web servers
9 | # and those relying on copy on write to perform better.
10 | # Rake tasks automatically ignore this option for performance.
11 | config.eager_load = true
12 |
13 | # Full error reports are disabled and caching is turned on.
14 | config.consider_all_requests_local = false
15 | config.action_controller.perform_caching = true
16 |
17 | # Enable Rack::Cache to put a simple HTTP cache in front of your application
18 | # Add `rack-cache` to your Gemfile before enabling this.
19 | # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
20 | # config.action_dispatch.rack_cache = true
21 |
22 | # Disable Rails's static asset server (Apache or nginx will already do this).
23 | config.serve_static_assets = false
24 |
25 | # Compress JavaScripts and CSS.
26 | config.assets.js_compressor = :uglifier
27 | # config.assets.css_compressor = :sass
28 |
29 | # Do not fallback to assets pipeline if a precompiled asset is missed.
30 | config.assets.compile = false
31 |
32 | # Generate digests for assets URLs.
33 | config.assets.digest = true
34 |
35 | # Version of your assets, change this if you want to expire all your assets.
36 | config.assets.version = '1.0'
37 |
38 | # Specifies the header that your server uses for sending files.
39 | # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
40 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
41 |
42 | # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
43 | # config.force_ssl = true
44 |
45 | # Set to :debug to see everything in the log.
46 | config.log_level = :info
47 |
48 | # Prepend all log lines with the following tags.
49 | # config.log_tags = [ :subdomain, :uuid ]
50 |
51 | # Use a different logger for distributed setups.
52 | # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
53 |
54 | # Use a different cache store in production.
55 | # config.cache_store = :mem_cache_store
56 |
57 | # Enable serving of images, stylesheets, and JavaScripts from an asset server.
58 | # config.action_controller.asset_host = "http://assets.example.com"
59 |
60 | # Precompile additional assets.
61 | # application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
62 | # config.assets.precompile += %w( search.js )
63 |
64 | # Ignore bad email addresses and do not raise email delivery errors.
65 | # Set this to true and configure the email server for immediate delivery to raise delivery errors.
66 | # config.action_mailer.raise_delivery_errors = false
67 |
68 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
69 | # the I18n.default_locale when a translation cannot be found).
70 | config.i18n.fallbacks = true
71 |
72 | # Send deprecation notices to registered listeners.
73 | config.active_support.deprecation = :notify
74 |
75 | # Disable automatic flushing of the log to improve performance.
76 | # config.autoflush_log = false
77 |
78 | # Use default logging formatter so that PID and timestamp are not suppressed.
79 | config.log_formatter = ::Logger::Formatter.new
80 |
81 | # Do not dump schema after migrations.
82 | config.active_record.dump_schema_after_migration = false
83 | end
84 |
--------------------------------------------------------------------------------
/config/locales/devise.en.yml:
--------------------------------------------------------------------------------
1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n
2 |
3 | en:
4 | devise:
5 | confirmations:
6 | confirmed: "Your account was successfully confirmed."
7 | send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
8 | send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
9 | failure:
10 | already_authenticated: "You are already signed in."
11 | inactive: "Your account is not activated yet."
12 | invalid: "Invalid email or password."
13 | locked: "Your account is locked."
14 | last_attempt: "You have one more attempt before your account will be locked."
15 | not_found_in_database: "Invalid email or password."
16 | timeout: "Your session expired. Please sign in again to continue."
17 | unauthenticated: "You need to sign in or sign up before continuing."
18 | unconfirmed: "You have to confirm your account before continuing."
19 | mailer:
20 | confirmation_instructions:
21 | subject: "Confirmation instructions"
22 | reset_password_instructions:
23 | subject: "Reset password instructions"
24 | unlock_instructions:
25 | subject: "Unlock Instructions"
26 | omniauth_callbacks:
27 | failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
28 | success: "Successfully authenticated from %{kind} account."
29 | passwords:
30 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
31 | send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
32 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
33 | updated: "Your password was changed successfully. You are now signed in."
34 | updated_not_active: "Your password was changed successfully."
35 | registrations:
36 | destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon."
37 | signed_up: "Welcome! You have signed up successfully."
38 | signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
39 | signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
40 | signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
41 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
42 | updated: "You updated your account successfully."
43 | sessions:
44 | signed_in: "Signed in successfully."
45 | signed_out: "Signed out successfully."
46 | unlocks:
47 | send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes."
48 | send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."
49 | unlocked: "Your account has been unlocked successfully. Please sign in to continue."
50 | errors:
51 | messages:
52 | already_confirmed: "was already confirmed, please try signing in"
53 | confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
54 | expired: "has expired, please request a new one"
55 | not_found: "not found"
56 | not_locked: "was not locked"
57 | not_saved:
58 | one: "1 error prohibited this %{resource} from being saved:"
59 | other: "%{count} errors prohibited this %{resource} from being saved:"
60 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Workshops application
2 |
3 | Hi! We think it’s great that you want to **join along with Netguru** to start learning **Ruby on Rails**. Taking part in workshops is also a **great opportunity to start an internship** with us and become one of the Netguru folks. Since you have just taken your first step on your adventure with programming in RoR, we challenge you to complete the following task. **Ready, steady…Go!**
4 |
5 | ### Let’s start with a setup:
6 |
7 | **Source code**
8 |
9 | Don't fork the repository. Clone it (`git clone git@github.com:netguru-training/workshops.git`) and make a new one – we want all of you to have equal chances.
10 |
11 | **Database**
12 |
13 | Copy the database config file (and edit if needed):
14 | ` cp config/database.yml.sample config/database.yml`
15 |
16 | Make sure the user you've listed in `database.yml` is created for postgres:
17 | `createuser -s -r workshops`
18 |
19 | Setup the database for your application (development and test environments):
20 | `bin/rake db:setup`
21 | `bin/rake db:test:prepare`
22 |
23 |
24 | ### Issues to solve:
25 |
26 | 1. There are a few missing fields on the `User` model. Make sure `spec/models/user_spec.rb passes.`
27 |
28 | 2. Make sure settings for [devise](https://github.com/plataformatec/devise) are
29 | configured properly. If they aren’t, most of the controller specs will fail:
30 | * Most of the configuration changes require the server to be restarted.
31 | * At some point **you'll have to overwrite the default devise views** - you can find all the required info in the gem readme.
32 |
33 | 3. Check `spec/controllers/categories_controller_spec.rb` - there should be a
34 | couple errors on actions checking admin presence.
35 |
36 | 4. Next up: `Product` model and `spec/models/product_spec.rb`. Play with validations a bit, calculate average rating and you'll be good to go.
37 |
38 | 5. Fix specs for `Category` model.
39 |
40 | 6. Fix specs for `Review` model.
41 |
42 | 7. You'll have to deal with `ProductsController`. Again, you'll have to check for permissions. Only a product owner should be able to make changes. Make sure to give the user a proper message when they try to perform forbidden actions.
43 |
44 | 8. Make sure `ReviewDecorator` is used properly, There's one action which needs to be declared there. See `spec/decorators/review_decorator_spec.rb` for details.
45 |
46 | 9. Check if each review is assigned to user who wrote it.
47 |
48 | 10. If some actions (like links to edit a page, create a new one) are not allowed for a particular user then please hide them in a template (for example with `if`).
49 |
50 | 11. In navigation bar insert links for guest users to login / signup and for users that are already logged in - to logout.
51 |
52 | 12. Don't forget to check if application works in the browser :).
53 |
54 | 13. Unleash your design skills. Add some CSS to the application to make it prettier (we won't say it's ugly, but you know, it's not a beauty [YET!]). Please use [Bootstrap 3](http://getbootstrap.com/css/) for styling, which is already added to application. Psss! Don't forget about styling `devise` views :).
55 |
56 | 14. Create user profile page (using Boostrap 3). Use your imagination about what should go there. You can start with name, email, etc.
57 |
58 | 15. On user profile list 5 last user's reviews with formated date (dd-mm-yy).
59 |
60 | 16. Fill `seeds.rb` with 5 accounts for user and one admin account to login and example category with products and reviews.
61 |
62 | 17. Make sure your project is available on Heroku with **seeds data**.
63 |
64 | ## What disqualifies your application
65 |
66 | 1. Tests are not passing.
67 |
68 | 2. Website doesn't work on Heroku.
69 |
70 | 3. Design is not finished.
71 |
72 | ### Here are some great resources to help you with kicking off your adventure with Ruby and Rails:
73 |
74 | * [http://www.codeschool.com/paths/ruby](http://www.codeschool.com/paths/ruby) - free Ruby and Rails courses available at the elementary level
75 | * you want to be sure your Ruby basis are solid? Check out the Ruby Koans - [http://rubykoans.com/](http://rubykoans.com/)
76 | * [http://guides.rubyonrails.org/](http://guides.rubyonrails.org/) - sooner or later this one will come in handy
77 | * not feeling comfortable with JavaScript / jQuery? CodeSchool can help you with this one too - [http://www.codeschool.com/courses/try-jquery](http://www.codeschool.com/courses/try-jquery)
78 |
79 | ## Good Luck!
80 |
81 | *We want all attendees at netguru workshops to have an awesome harassment-free experience. Read our full [code of conduct](https://github.com/netguru-training/workshops/blob/master/code_of_conduct.md) for more details.*
82 |
--------------------------------------------------------------------------------
/config/initializers/simple_form_bootstrap.rb:
--------------------------------------------------------------------------------
1 | # Use this setup block to configure all options available in SimpleForm.
2 | SimpleForm.setup do |config|
3 | config.error_notification_class = 'alert alert-danger'
4 | config.button_class = 'btn btn-default'
5 | config.boolean_label_class = nil
6 |
7 | config.wrappers :vertical_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
8 | b.use :html5
9 | b.use :placeholder
10 | b.optional :maxlength
11 | b.optional :pattern
12 | b.optional :min_max
13 | b.optional :readonly
14 | b.use :label, class: 'control-label'
15 |
16 | b.use :input, class: 'form-control'
17 | b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
18 | b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
19 | end
20 |
21 | config.wrappers :vertical_file_input, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
22 | b.use :html5
23 | b.use :placeholder
24 | b.optional :maxlength
25 | b.optional :readonly
26 | b.use :label, class: 'control-label'
27 |
28 | b.use :input
29 | b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
30 | b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
31 | end
32 |
33 | config.wrappers :vertical_boolean, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
34 | b.use :html5
35 | b.optional :readonly
36 |
37 | b.wrapper tag: 'div', class: 'checkbox' do |ba|
38 | ba.use :label_input
39 | end
40 |
41 | b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
42 | b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
43 | end
44 |
45 | config.wrappers :vertical_radio_and_checkboxes, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
46 | b.use :html5
47 | b.optional :readonly
48 | b.use :label_input
49 | b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
50 | b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
51 | end
52 |
53 | config.wrappers :horizontal_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
54 | b.use :html5
55 | b.use :placeholder
56 | b.optional :maxlength
57 | b.optional :pattern
58 | b.optional :min_max
59 | b.optional :readonly
60 | b.use :label, class: 'col-sm-3 control-label'
61 |
62 | b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
63 | ba.use :input, class: 'form-control'
64 | ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
65 | ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
66 | end
67 | end
68 |
69 | config.wrappers :horizontal_file_input, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
70 | b.use :html5
71 | b.use :placeholder
72 | b.optional :maxlength
73 | b.optional :readonly
74 | b.use :label, class: 'col-sm-3 control-label'
75 |
76 | b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
77 | ba.use :input
78 | ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
79 | ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
80 | end
81 | end
82 |
83 | config.wrappers :horizontal_boolean, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
84 | b.use :html5
85 | b.optional :readonly
86 |
87 | b.wrapper tag: 'div', class: 'col-sm-offset-3 col-sm-9' do |wr|
88 | wr.wrapper tag: 'div', class: 'checkbox' do |ba|
89 | ba.use :label_input, class: 'col-sm-9'
90 | end
91 |
92 | wr.use :error, wrap_with: { tag: 'span', class: 'help-block' }
93 | wr.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
94 | end
95 | end
96 |
97 | config.wrappers :horizontal_radio_and_checkboxes, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
98 | b.use :html5
99 | b.optional :readonly
100 |
101 | b.use :label, class: 'col-sm-3 control-label'
102 |
103 | b.wrapper tag: 'div', class: 'col-sm-9' do |ba|
104 | ba.use :input
105 | ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
106 | ba.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
107 | end
108 | end
109 |
110 | config.wrappers :inline_form, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
111 | b.use :html5
112 | b.use :placeholder
113 | b.optional :maxlength
114 | b.optional :pattern
115 | b.optional :min_max
116 | b.optional :readonly
117 | b.use :label, class: 'sr-only'
118 |
119 | b.use :input, class: 'form-control'
120 | b.use :error, wrap_with: { tag: 'span', class: 'help-block' }
121 | b.use :hint, wrap_with: { tag: 'p', class: 'help-block' }
122 | end
123 |
124 | # Wrappers for forms and inputs using the Bootstrap toolkit.
125 | # Check the Bootstrap docs (http://getbootstrap.com)
126 | # to learn about the different styles for forms and inputs,
127 | # buttons and other elements.
128 | config.default_wrapper = :vertical_form
129 | end
130 |
--------------------------------------------------------------------------------
/spec/controllers/categories_controller_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe CategoriesController do
4 |
5 | let(:valid_attributes) { { name: 'MyString'} }
6 |
7 | let(:valid_session) { {} }
8 |
9 | let(:user) { build(:user) }
10 |
11 | before do
12 | sign_in user
13 | controller.stub(:user_signed_in?).and_return(true)
14 | controller.stub(:current_user).and_return(user)
15 | controller.stub(:authenticate_user!).and_return(user)
16 | end
17 |
18 | context 'user is not an admin' do
19 | before do
20 | controller.current_user.stub(admin?: false)
21 | end
22 |
23 | describe 'GET new' do
24 | it 'redirects user to the login page' do
25 | get :new, {}, valid_session
26 | expect(response).to redirect_to(new_user_session_path)
27 | end
28 | end
29 |
30 | describe 'GET edit' do
31 | it 'redirects user to the login page' do
32 | category = Category.create! valid_attributes
33 | get :edit, { id: category.to_param }, valid_session
34 | expect(response).to redirect_to(new_user_session_path)
35 | end
36 | end
37 |
38 | describe 'POST create' do
39 | it 'redirects user to the login page' do
40 | post :create, {category: valid_attributes}, valid_session
41 | expect(response).to redirect_to(new_user_session_path)
42 | end
43 | end
44 |
45 | describe 'PUT update' do
46 | it 'redirect user to the login page' do
47 | category = Category.create! valid_attributes
48 | put :update, {:id => category.to_param, :category => { 'name' => 'MyString'}}, valid_session
49 | expect(response).to redirect_to(new_user_session_path)
50 | end
51 | end
52 | end
53 |
54 | context 'user is an admin' do
55 | before do
56 | controller.current_user.stub(admin?: true)
57 | end
58 |
59 | describe 'GET index' do
60 | it 'exposes all categories' do
61 | category = Category.create! valid_attributes
62 | get :index, {}, valid_session
63 | expect(controller.categories).to eq([category])
64 | end
65 | end
66 |
67 | describe 'GET show' do
68 | it 'exposes the requested category' do
69 | category = Category.create! valid_attributes
70 | get :show, { id: category.to_param }, valid_session
71 | expect(controller.category).to eq(category)
72 | end
73 | end
74 |
75 | describe 'GET new' do
76 | it 'exposes a new category' do
77 | get :new, {}, valid_session
78 | expect(controller.category).to be_a_new(Category)
79 | end
80 | end
81 |
82 | describe 'GET edit' do
83 | it 'exposes the requested category' do
84 | category = Category.create! valid_attributes
85 | get :edit, { id: category.to_param }, valid_session
86 | expect(controller.category).to eq(category)
87 | end
88 | end
89 |
90 | describe 'POST create' do
91 | describe 'with valid params' do
92 | it 'creates a new Category' do
93 | expect {
94 | post :create, {category: valid_attributes}, valid_session
95 | }.to change(Category, :count).by(1)
96 | end
97 |
98 | it 'exposes a newly created category as #category' do
99 | post :create, {category: valid_attributes}, valid_session
100 | expect(controller.category).to be_a(Category)
101 | expect(controller.category).to be_persisted
102 | end
103 |
104 | it 'redirects to the created category' do
105 | post :create, {category: valid_attributes}, valid_session
106 | expect(response).to redirect_to(Category.last)
107 | end
108 | end
109 |
110 | describe 'with invalid params' do
111 | it 'exposes a newly created but unsaved category' do
112 | Category.any_instance.stub(:save).and_return(false)
113 | post :create, {category: { 'name' => 'invalid value'}}, valid_session
114 | expect(controller.category).to be_a_new(Category)
115 | end
116 |
117 | it "re-renders the 'new' template" do
118 | Category.any_instance.stub(:save).and_return(false)
119 | post :create, {category: { 'name' => 'invalid value'}}, valid_session
120 | expect(response).to render_template('new')
121 | end
122 | end
123 | end
124 |
125 | describe 'PUT update' do
126 | let(:category) { Category.create! valid_attributes }
127 | describe 'with valid params' do
128 | it 'updates the requested category' do
129 | Category.any_instance.should_receive(:update).with({ 'name' => 'MyString'})
130 | put :update, {:id => category.to_param, :category => { 'name' => 'MyString'}}, valid_session
131 | end
132 |
133 | it 'exposes the requested category' do
134 | put :update, {:id => category.to_param, :category => valid_attributes}, valid_session
135 | expect(controller.category).to eq(category)
136 | end
137 |
138 | it 'redirects to the category' do
139 | put :update, {:id => category.to_param, :category => valid_attributes}, valid_session
140 | response.should redirect_to(category)
141 | end
142 | end
143 |
144 | describe 'with invalid params' do
145 | it 'exposes the category' do
146 | Category.any_instance.stub(:save).and_return(false)
147 | put :update, {:id => category.to_param, :category => { 'name' => 'invalid value'}}, valid_session
148 | expect(controller.category).to eq(category)
149 | end
150 |
151 | it "re-renders the 'edit' template" do
152 | Category.any_instance.stub(:save).and_return(false)
153 | put :update, {:id => category.to_param, :category => { 'name' => 'invalid value'}}, valid_session
154 | response.should render_template('edit')
155 | end
156 | end
157 | end
158 |
159 | describe 'DELETE destroy' do
160 | let!(:category) { Category.create! valid_attributes }
161 |
162 | it 'destroys the requested category' do
163 | expect {
164 | delete :destroy, {:id => category.to_param}, valid_session
165 | }.to change(Category, :count).by(-1)
166 | end
167 |
168 | it 'redirects to the categories list' do
169 | delete :destroy, {:id => category.to_param}, valid_session
170 | response.should redirect_to(categories_url)
171 | end
172 | end
173 | end
174 |
175 | end
176 |
--------------------------------------------------------------------------------
/Gemfile.lock:
--------------------------------------------------------------------------------
1 | GIT
2 | remote: git://github.com/rails/sass-rails.git
3 | revision: 404cd9ba2bf2618fe14b1ba2f27c861ba48980f2
4 | specs:
5 | sass-rails (5.0.0.beta1)
6 | railties (>= 4.0.0, < 5.0)
7 | sass (~> 3.2, >= 3.2.2)
8 | sprockets (~> 2.8, < 3.0)
9 | sprockets-rails (>= 2.0, < 4.0)
10 |
11 | GEM
12 | remote: https://rubygems.org/
13 | specs:
14 | actionmailer (4.1.8)
15 | actionpack (= 4.1.8)
16 | actionview (= 4.1.8)
17 | mail (~> 2.5, >= 2.5.4)
18 | actionpack (4.1.8)
19 | actionview (= 4.1.8)
20 | activesupport (= 4.1.8)
21 | rack (~> 1.5.2)
22 | rack-test (~> 0.6.2)
23 | actionview (4.1.8)
24 | activesupport (= 4.1.8)
25 | builder (~> 3.1)
26 | erubis (~> 2.7.0)
27 | activemodel (4.1.8)
28 | activesupport (= 4.1.8)
29 | builder (~> 3.1)
30 | activerecord (4.1.8)
31 | activemodel (= 4.1.8)
32 | activesupport (= 4.1.8)
33 | arel (~> 5.0.0)
34 | activesupport (4.1.8)
35 | i18n (~> 0.6, >= 0.6.9)
36 | json (~> 1.7, >= 1.7.7)
37 | minitest (~> 5.1)
38 | thread_safe (~> 0.1)
39 | tzinfo (~> 1.1)
40 | addressable (2.3.6)
41 | arel (5.0.1.20140414130214)
42 | backports (3.6.4)
43 | bcrypt (3.1.9)
44 | bootstrap-sass (3.1.1.1)
45 | sass (~> 3.2)
46 | builder (3.2.2)
47 | coderay (1.1.0)
48 | coffee-rails (4.1.0)
49 | coffee-script (>= 2.2.0)
50 | railties (>= 4.0.0, < 5.0)
51 | coffee-script (2.3.0)
52 | coffee-script-source
53 | execjs
54 | coffee-script-source (1.8.0)
55 | database_cleaner (1.3.0)
56 | decent_decoration (0.0.6)
57 | decent_exposure (>= 2.0)
58 | decent_exposure (2.3.2)
59 | devise (3.4.1)
60 | bcrypt (~> 3.0)
61 | orm_adapter (~> 0.1)
62 | railties (>= 3.2.6, < 5)
63 | responders
64 | thread_safe (~> 0.1)
65 | warden (~> 1.2.3)
66 | diff-lcs (1.2.5)
67 | draper (1.4.0)
68 | actionpack (>= 3.0)
69 | activemodel (>= 3.0)
70 | activesupport (>= 3.0)
71 | request_store (~> 1.0)
72 | erubis (2.7.0)
73 | ethon (0.7.1)
74 | ffi (>= 1.3.0)
75 | execjs (2.2.2)
76 | factory_girl (4.5.0)
77 | activesupport (>= 3.0.0)
78 | factory_girl_rails (4.5.0)
79 | factory_girl (~> 4.5.0)
80 | railties (>= 3.0.0)
81 | faraday (0.9.0)
82 | multipart-post (>= 1.2, < 3)
83 | faraday_middleware (0.9.1)
84 | faraday (>= 0.7.4, < 0.10)
85 | ffaker (1.25.0)
86 | ffi (1.9.6)
87 | gh (0.13.2)
88 | addressable
89 | backports
90 | faraday (~> 0.8)
91 | multi_json (~> 1.0)
92 | net-http-persistent (>= 2.7)
93 | net-http-pipeline
94 | haml (4.0.5)
95 | tilt
96 | haml-rails (0.5.3)
97 | actionpack (>= 4.0.1)
98 | activesupport (>= 4.0.1)
99 | haml (>= 3.1, < 5.0)
100 | railties (>= 4.0.1)
101 | highline (1.6.21)
102 | hike (1.2.3)
103 | i18n (0.6.11)
104 | jquery-rails (3.1.2)
105 | railties (>= 3.0, < 5.0)
106 | thor (>= 0.14, < 2.0)
107 | json (1.8.1)
108 | konf (0.0.2)
109 | launchy (2.4.3)
110 | addressable (~> 2.3)
111 | libv8 (3.16.14.7)
112 | mail (2.6.3)
113 | mime-types (>= 1.16, < 3)
114 | method_source (0.8.2)
115 | mime-types (2.4.3)
116 | minitest (5.4.3)
117 | multi_json (1.10.1)
118 | multipart-post (2.0.0)
119 | net-http-persistent (2.9.4)
120 | net-http-pipeline (1.0.1)
121 | orm_adapter (0.5.0)
122 | pg (0.17.1)
123 | pry (0.9.12.6)
124 | coderay (~> 1.0)
125 | method_source (~> 0.8)
126 | slop (~> 3.4)
127 | pusher-client (0.6.0)
128 | json
129 | websocket (~> 1.0)
130 | quiet_assets (1.0.3)
131 | railties (>= 3.1, < 5.0)
132 | rack (1.5.2)
133 | rack-test (0.6.2)
134 | rack (>= 1.0)
135 | rails (4.1.8)
136 | actionmailer (= 4.1.8)
137 | actionpack (= 4.1.8)
138 | actionview (= 4.1.8)
139 | activemodel (= 4.1.8)
140 | activerecord (= 4.1.8)
141 | activesupport (= 4.1.8)
142 | bundler (>= 1.3.0, < 2.0)
143 | railties (= 4.1.8)
144 | sprockets-rails (~> 2.0)
145 | railties (4.1.8)
146 | actionpack (= 4.1.8)
147 | activesupport (= 4.1.8)
148 | rake (>= 0.8.7)
149 | thor (>= 0.18.1, < 2.0)
150 | rake (10.3.2)
151 | ref (1.0.5)
152 | request_store (1.1.0)
153 | responders (1.1.2)
154 | railties (>= 3.2, < 4.2)
155 | rspec-core (3.1.7)
156 | rspec-support (~> 3.1.0)
157 | rspec-expectations (3.1.2)
158 | diff-lcs (>= 1.2.0, < 2.0)
159 | rspec-support (~> 3.1.0)
160 | rspec-mocks (3.1.3)
161 | rspec-support (~> 3.1.0)
162 | rspec-rails (3.1.0)
163 | actionpack (>= 3.0)
164 | activesupport (>= 3.0)
165 | railties (>= 3.0)
166 | rspec-core (~> 3.1.0)
167 | rspec-expectations (~> 3.1.0)
168 | rspec-mocks (~> 3.1.0)
169 | rspec-support (~> 3.1.0)
170 | rspec-support (3.1.2)
171 | sass (3.4.8)
172 | shoulda-matchers (2.7.0)
173 | activesupport (>= 3.0.0)
174 | simple_form (3.1.0.rc2)
175 | actionpack (~> 4.0)
176 | activemodel (~> 4.0)
177 | slop (3.6.0)
178 | spring (1.2.0)
179 | sprockets (2.12.3)
180 | hike (~> 1.2)
181 | multi_json (~> 1.0)
182 | rack (~> 1.0)
183 | tilt (~> 1.1, != 1.3.0)
184 | sprockets-rails (2.2.1)
185 | actionpack (>= 3.0)
186 | activesupport (>= 3.0)
187 | sprockets (>= 2.8, < 4.0)
188 | therubyracer (0.12.1)
189 | libv8 (~> 3.16.14.0)
190 | ref
191 | thor (0.19.1)
192 | thread_safe (0.3.4)
193 | tilt (1.4.1)
194 | travis (1.7.4)
195 | addressable (~> 2.3)
196 | backports
197 | faraday (~> 0.9)
198 | faraday_middleware (~> 0.9, >= 0.9.1)
199 | gh (~> 0.13)
200 | highline (~> 1.6)
201 | launchy (~> 2.1)
202 | pry (~> 0.9, < 0.10)
203 | pusher-client (~> 0.4)
204 | typhoeus (~> 0.6, >= 0.6.8)
205 | typhoeus (0.6.9)
206 | ethon (>= 0.7.1)
207 | tzinfo (1.2.2)
208 | thread_safe (~> 0.1)
209 | uglifier (2.5.3)
210 | execjs (>= 0.3.0)
211 | json (>= 1.8.0)
212 | warden (1.2.3)
213 | rack (>= 1.0)
214 | websocket (1.2.1)
215 |
216 | PLATFORMS
217 | ruby
218 |
219 | DEPENDENCIES
220 | bootstrap-sass (~> 3.1.0)
221 | coffee-rails
222 | database_cleaner
223 | decent_decoration
224 | decent_exposure
225 | devise
226 | draper
227 | factory_girl_rails
228 | ffaker
229 | haml-rails
230 | jquery-rails
231 | konf
232 | pg
233 | pry
234 | quiet_assets
235 | rails (= 4.1.8)
236 | rspec-rails
237 | sass-rails!
238 | shoulda-matchers
239 | simple_form (~> 3.1.0rc)
240 | spring
241 | therubyracer
242 | travis
243 | uglifier
244 |
--------------------------------------------------------------------------------
/config/initializers/simple_form.rb:
--------------------------------------------------------------------------------
1 | # Use this setup block to configure all options available in SimpleForm.
2 | SimpleForm.setup do |config|
3 | # Wrappers are used by the form builder to generate a
4 | # complete input. You can remove any component from the
5 | # wrapper, change the order or even add your own to the
6 | # stack. The options given below are used to wrap the
7 | # whole input.
8 | config.wrappers :default, class: :input,
9 | hint_class: :field_with_hint, error_class: :field_with_errors do |b|
10 | ## Extensions enabled by default
11 | # Any of these extensions can be disabled for a
12 | # given input by passing: `f.input EXTENSION_NAME => false`.
13 | # You can make any of these extensions optional by
14 | # renaming `b.use` to `b.optional`.
15 |
16 | # Determines whether to use HTML5 (:email, :url, ...)
17 | # and required attributes
18 | b.use :html5
19 |
20 | # Calculates placeholders automatically from I18n
21 | # You can also pass a string as f.input placeholder: "Placeholder"
22 | b.use :placeholder
23 |
24 | ## Optional extensions
25 | # They are disabled unless you pass `f.input EXTENSION_NAME => true`
26 | # to the input. If so, they will retrieve the values from the model
27 | # if any exists. If you want to enable any of those
28 | # extensions by default, you can change `b.optional` to `b.use`.
29 |
30 | # Calculates maxlength from length validations for string inputs
31 | b.optional :maxlength
32 |
33 | # Calculates pattern from format validations for string inputs
34 | b.optional :pattern
35 |
36 | # Calculates min and max from length validations for numeric inputs
37 | b.optional :min_max
38 |
39 | # Calculates readonly automatically from readonly attributes
40 | b.optional :readonly
41 |
42 | ## Inputs
43 | b.use :label_input
44 | b.use :hint, wrap_with: { tag: :span, class: :hint }
45 | b.use :error, wrap_with: { tag: :span, class: :error }
46 |
47 | ## full_messages_for
48 | # If you want to display the full error message for the attribute, you can
49 | # use the component :full_error, like:
50 | #
51 | # b.use :full_error, wrap_with: { tag: :span, class: :error }
52 | end
53 |
54 | # The default wrapper to be used by the FormBuilder.
55 | config.default_wrapper = :default
56 |
57 | # Define the way to render check boxes / radio buttons with labels.
58 | # Defaults to :nested for bootstrap config.
59 | # inline: input + label
60 | # nested: label > input
61 | config.boolean_style = :nested
62 |
63 | # Default class for buttons
64 | config.button_class = 'btn'
65 |
66 | # Method used to tidy up errors. Specify any Rails Array method.
67 | # :first lists the first message for each field.
68 | # Use :to_sentence to list all errors for each field.
69 | # config.error_method = :first
70 |
71 | # Default tag used for error notification helper.
72 | config.error_notification_tag = :div
73 |
74 | # CSS class to add for error notification helper.
75 | config.error_notification_class = 'error_notification'
76 |
77 | # ID to add for error notification helper.
78 | # config.error_notification_id = nil
79 |
80 | # Series of attempts to detect a default label method for collection.
81 | # config.collection_label_methods = [ :to_label, :name, :title, :to_s ]
82 |
83 | # Series of attempts to detect a default value method for collection.
84 | # config.collection_value_methods = [ :id, :to_s ]
85 |
86 | # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
87 | # config.collection_wrapper_tag = nil
88 |
89 | # You can define the class to use on all collection wrappers. Defaulting to none.
90 | # config.collection_wrapper_class = nil
91 |
92 | # You can wrap each item in a collection of radio/check boxes with a tag,
93 | # defaulting to :span. Please note that when using :boolean_style = :nested,
94 | # SimpleForm will force this option to be a label.
95 | # config.item_wrapper_tag = :span
96 |
97 | # You can define a class to use in all item wrappers. Defaulting to none.
98 | # config.item_wrapper_class = nil
99 |
100 | # How the label text should be generated altogether with the required text.
101 | # config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
102 |
103 | # You can define the class to use on all labels. Default is nil.
104 | # config.label_class = nil
105 |
106 | # You can define the class to use on all forms. Default is simple_form.
107 | # config.form_class = :simple_form
108 |
109 | # You can define which elements should obtain additional classes
110 | # config.generate_additional_classes_for = [:wrapper, :label, :input]
111 |
112 | # Whether attributes are required by default (or not). Default is true.
113 | # config.required_by_default = true
114 |
115 | # Tell browsers whether to use the native HTML5 validations (novalidate form option).
116 | # These validations are enabled in SimpleForm's internal config but disabled by default
117 | # in this configuration, which is recommended due to some quirks from different browsers.
118 | # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations,
119 | # change this configuration to true.
120 | config.browser_validations = false
121 |
122 | # Collection of methods to detect if a file type was given.
123 | # config.file_methods = [ :mounted_as, :file?, :public_filename ]
124 |
125 | # Custom mappings for input types. This should be a hash containing a regexp
126 | # to match as key, and the input type that will be used when the field name
127 | # matches the regexp as value.
128 | # config.input_mappings = { /count/ => :integer }
129 |
130 | # Custom wrappers for input types. This should be a hash containing an input
131 | # type as key and the wrapper that will be used for all inputs with specified type.
132 | # config.wrapper_mappings = { string: :prepend }
133 |
134 | # Namespaces where SimpleForm should look for custom input classes that
135 | # override default inputs.
136 | # config.custom_inputs_namespaces << "CustomInputs"
137 |
138 | # Default priority for time_zone inputs.
139 | # config.time_zone_priority = nil
140 |
141 | # Default priority for country inputs.
142 | # config.country_priority = nil
143 |
144 | # When false, do not use translations for labels.
145 | # config.translate_labels = true
146 |
147 | # Automatically discover new inputs in Rails' autoload path.
148 | # config.inputs_discovery = true
149 |
150 | # Cache SimpleForm inputs discovery
151 | # config.cache_discovery = !Rails.env.development?
152 |
153 | # Default class for inputs
154 | # config.input_class = nil
155 |
156 | # Define the default class of the input wrapper of the boolean input.
157 | config.boolean_label_class = 'checkbox'
158 |
159 | # Defines if the default input wrapper class should be included in radio
160 | # collection wrappers.
161 | # config.include_default_input_wrapper_class = true
162 |
163 | # Defines which i18n scope will be used in Simple Form.
164 | # config.i18n_scope = 'simple_form'
165 | end
166 |
--------------------------------------------------------------------------------
/spec/controllers/products_controller_spec.rb:
--------------------------------------------------------------------------------
1 | require 'spec_helper'
2 |
3 | describe ProductsController do
4 | let(:category) { create(:category) }
5 | let(:valid_attributes) do
6 | {
7 | title: 'MyString',
8 | description: 'Some description',
9 | price: 2.5,
10 | category_id: category.id,
11 | }
12 | end
13 |
14 | context 'user is not signed in' do
15 | describe 'POST create' do
16 | describe 'with valid params' do
17 | it 'redirects user to login page' do
18 | post :create, { product: valid_attributes, category_id: category.to_param }
19 | expect(response).to redirect_to(new_user_session_path)
20 | end
21 | end
22 | end
23 |
24 | describe 'PUT update' do
25 | describe 'with valid params' do
26 | it 'redirects user to login page' do
27 | product = Product.create! valid_attributes
28 | put :update, { id: product.to_param, product: { title: 'MyString' }, category_id: category.to_param }
29 | expect(response).to redirect_to(new_user_session_path)
30 | end
31 | end
32 | end
33 | end
34 |
35 | context 'another user is signed in' do
36 | let(:user) { create(:user) }
37 | let(:user2) { build(:user) }
38 | let(:product) { Product.create! valid_attributes }
39 |
40 | before do
41 | sign_in user2
42 | controller.stub(:user_signed_in?).and_return(true)
43 | controller.stub(:current_user).and_return(user2)
44 | controller.stub(:authenticate_user!).and_return(user2)
45 | product.user = user
46 | end
47 |
48 | describe 'GET edit' do
49 | describe 'with valid params' do
50 | it 'redirects to product page' do
51 | get :edit, { id: product.to_param, category_id: category.to_param }
52 | expect(response).to redirect_to(category_product_url(category, product))
53 | end
54 |
55 | it 'renders error message' do
56 | get :edit, { id: product.to_param, category_id: category.to_param }
57 | expect(controller.flash[:error]).to eq 'You are not allowed to edit this product.'
58 | end
59 | end
60 | end
61 |
62 | describe 'PUT update' do
63 | describe 'with valid params' do
64 | it 'redirects to product page' do
65 | put :update, { id: product.to_param, product: { 'title' => 'MyString' }, category_id: category.to_param }
66 | expect(response).to redirect_to(category_product_url(category, product))
67 | end
68 |
69 | it 'does not update product' do
70 | put :update, { id: product.to_param, product: { 'title' => 'MyNewString' }, category_id: category.to_param }
71 | expect(controller.product.title).to_not eq 'MyNewString'
72 | end
73 |
74 | it 'renders error message' do
75 | put :update, { id: product.to_param, product: { 'title' => 'MyString' }, category_id: category.to_param }
76 | expect(controller.flash[:error]).to eq 'You are not allowed to edit this product.'
77 | end
78 | end
79 | end
80 | end
81 |
82 | describe 'GET index' do
83 | it 'expose all products' do
84 | product = Product.create! valid_attributes
85 | product.category = category
86 | get :index, category_id: category.id
87 | expect(controller.products).to eq([product])
88 | end
89 | end
90 |
91 | describe 'GET show' do
92 | it 'expose the requested product' do
93 | product = Product.create! valid_attributes
94 | get :show, { id: product.to_param, category_id: category.to_param }
95 | expect(controller.product).to eq(product)
96 | end
97 | end
98 |
99 | describe 'GET new' do
100 | it 'expose a new product' do
101 | get :new, { category_id: category.to_param }
102 | expect(controller.product).to be_a_new(Product)
103 | end
104 | end
105 |
106 | describe 'GET edit' do
107 | it 'expose the requested product' do
108 | product = Product.create! valid_attributes
109 | get :edit, { id: product.to_param, category_id: category.to_param }
110 | expect(controller.product).to eq(product)
111 | end
112 | end
113 |
114 | describe 'POST create' do
115 | describe 'with valid params' do
116 | context 'user is signed in' do
117 | let(:user) { create(:user) }
118 | let(:product) { Product.create! valid_attributes }
119 |
120 | before do
121 | sign_in user
122 | controller.stub(:user_signed_in?).and_return(true)
123 | controller.stub(:current_user).and_return(user)
124 | controller.stub(:authenticate_user!).and_return(user)
125 | product.user = user
126 | end
127 |
128 | it 'creates a new Product' do
129 | expect {
130 | post :create, { product: valid_attributes, category_id: category.to_param }
131 | }.to change(Product, :count).by(1)
132 | end
133 |
134 | it 'expose a newly created product' do
135 | post :create, { product: valid_attributes, category_id: category.to_param }
136 | expect(controller.product).to be_a(Product)
137 | expect(controller.product).to be_persisted
138 | end
139 |
140 | it 'redirects to the created product' do
141 | post :create, { product: valid_attributes, category_id: category.to_param }
142 | expect(response).to redirect_to(category_product_url(category, Product.last))
143 | end
144 |
145 | describe 'with invalid params' do
146 | it 'expose a newly created but unsaved product' do
147 |
148 | Product.any_instance.stub(:save).and_return(false)
149 | post :create, { product: { 'title' => 'invalid value' }, category_id: category.to_param }
150 | expect(controller.product).to be_a_new(Product)
151 | end
152 |
153 | it "re-renders the 'new' template" do
154 | Product.any_instance.stub(:save).and_return(false)
155 | post :create, { product: { 'title' => 'invalid value' }, category_id: category.to_param }
156 | expect(response).to render_template('new')
157 | end
158 | end
159 | end
160 | end
161 | end
162 |
163 | describe 'PUT update' do
164 | context 'user is signed in' do
165 | let(:user) { create(:user) }
166 | let(:product) { Product.create! valid_attributes }
167 |
168 | before do
169 | sign_in user
170 | controller.stub(:user_signed_in?).and_return(true)
171 | controller.stub(:current_user).and_return(user)
172 | controller.stub(:authenticate_user!).and_return(user)
173 | product.user = user
174 | end
175 |
176 | describe 'with valid params' do
177 | it 'updates the requested product' do
178 | Product.any_instance.stub(:save).and_return(true)
179 | put :update, { id: product.to_param, product: { 'title' => 'New value' }, category_id: category.to_param }
180 | expect(response).to redirect_to(category_product_path(category, product))
181 | end
182 |
183 | it 'expose the requested product' do
184 | put :update, { id: product.to_param, product: valid_attributes, category_id: category.to_param }
185 | expect(controller.product).to eq(product)
186 | end
187 |
188 | it 'redirects to the product' do
189 | put :update, { id: product.to_param, product: valid_attributes, category_id: category.to_param }
190 | expect(response).to redirect_to(category_product_url(category, product))
191 | end
192 | end
193 |
194 | describe 'with invalid params' do
195 | it 'expose the product' do
196 | Product.any_instance.stub(:save).and_return(false)
197 | put :update, { id: product.to_param, product: { 'title' => 'invalid value' }, category_id: category.to_param }
198 | expect(controller.product).to eq(product)
199 | end
200 |
201 | it "re-renders the 'edit' template" do
202 | Product.any_instance.stub(:save).and_return(false)
203 | put :update, { id: product.to_param, product: { 'title' => 'invalid value' }, category_id: category.to_param }
204 | expect(response).to redirect_to(category_product_url(category, product))
205 | end
206 | end
207 | end
208 | end
209 |
210 | describe 'DELETE destroy' do
211 | let(:user) { create(:user) }
212 | let(:category) { create(:category) }
213 | let(:product) { create(:product, user: user, category: category) }
214 |
215 | context 'user is signed in' do
216 | before do
217 | sign_in user
218 | controller.stub(:user_signed_in?).and_return(true)
219 | controller.stub(:current_user).and_return(user)
220 | controller.stub(:authenticate_user!).and_return(user)
221 | product.user = user
222 | end
223 |
224 | it 'destroys the requested product' do
225 | expect {
226 | delete :destroy, { id: product.to_param, category_id: category.to_param }
227 | }.to change(Product, :count).by(-1)
228 | end
229 |
230 | it 'redirects to the category page' do
231 | delete :destroy, { id: product.to_param, category_id: category.to_param }
232 | expect(response).to redirect_to(category_url(category))
233 | end
234 | end
235 |
236 | context 'user is not signed in' do
237 | it 'redirects user to login page' do
238 | delete :destroy, { id: product.to_param, category_id: category.to_param }
239 | expect(response).to redirect_to(new_user_session_path)
240 | end
241 | end
242 | end
243 |
244 | end
245 |
--------------------------------------------------------------------------------
/config/initializers/devise.rb:
--------------------------------------------------------------------------------
1 | # Use this hook to configure devise mailer, warden hooks and so forth.
2 | # Many of these configuration options can be set straight in your model.
3 | Devise.setup do |config|
4 | # The secret key used by Devise. Devise uses this key to generate
5 | # random tokens. Changing this key will render invalid all existing
6 | # confirmation, reset password and unlock tokens in the database.
7 | # config.secret_key = 'cfa9cae1b62d4914b2f06814543e3f192c5bf7921d4d82a40d679664c63d28a8bf8f050930a027247250622c05e850e1226cf9562121e02df0fab3d5403b244d'
8 |
9 | # ==> Mailer Configuration
10 | # Configure the e-mail address which will be shown in Devise::Mailer,
11 | # note that it will be overwritten if you use your own mailer class
12 | # with default "from" parameter.
13 | config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
14 |
15 | # Configure the class responsible to send e-mails.
16 | # config.mailer = 'Devise::Mailer'
17 |
18 | # ==> ORM configuration
19 | # Load and configure the ORM. Supports :active_record (default) and
20 | # :mongoid (bson_ext recommended) by default. Other ORMs may be
21 | # available as additional gems.
22 | require 'devise/orm/active_record'
23 |
24 | # ==> Configuration for any authentication mechanism
25 | # Configure which keys are used when authenticating a user. The default is
26 | # just :email. You can configure it to use [:username, :subdomain], so for
27 | # authenticating a user, both parameters are required. Remember that those
28 | # parameters are used only when authenticating and not when retrieving from
29 | # session. If you need permissions, you should implement that in a before filter.
30 | # You can also supply a hash where the value is a boolean determining whether
31 | # or not authentication should be aborted when the value is not present.
32 | # config.authentication_keys = [ :email ]
33 |
34 | # Configure parameters from the request object used for authentication. Each entry
35 | # given should be a request method and it will automatically be passed to the
36 | # find_for_authentication method and considered in your model lookup. For instance,
37 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
38 | # The same considerations mentioned for authentication_keys also apply to request_keys.
39 | # config.request_keys = []
40 |
41 | # Configure which authentication keys should be case-insensitive.
42 | # These keys will be downcased upon creating or modifying a user and when used
43 | # to authenticate or find a user. Default is :email.
44 | config.case_insensitive_keys = [ :email ]
45 |
46 | # Configure which authentication keys should have whitespace stripped.
47 | # These keys will have whitespace before and after removed upon creating or
48 | # modifying a user and when used to authenticate or find a user. Default is :email.
49 | config.strip_whitespace_keys = [ :email ]
50 |
51 | # Tell if authentication through request.params is enabled. True by default.
52 | # It can be set to an array that will enable params authentication only for the
53 | # given strategies, for example, `config.params_authenticatable = [:database]` will
54 | # enable it only for database (email + password) authentication.
55 | # config.params_authenticatable = true
56 |
57 | # Tell if authentication through HTTP Auth is enabled. False by default.
58 | # It can be set to an array that will enable http authentication only for the
59 | # given strategies, for example, `config.http_authenticatable = [:database]` will
60 | # enable it only for database authentication. The supported strategies are:
61 | # :database = Support basic authentication with authentication key + password
62 | # config.http_authenticatable = false
63 |
64 | # If http headers should be returned for AJAX requests. True by default.
65 | # config.http_authenticatable_on_xhr = true
66 |
67 | # The realm used in Http Basic Authentication. 'Application' by default.
68 | # config.http_authentication_realm = 'Application'
69 |
70 | # It will change confirmation, password recovery and other workflows
71 | # to behave the same regardless if the e-mail provided was right or wrong.
72 | # Does not affect registerable.
73 | # config.paranoid = true
74 |
75 | # By default Devise will store the user in session. You can skip storage for
76 | # particular strategies by setting this option.
77 | # Notice that if you are skipping storage for all authentication paths, you
78 | # may want to disable generating routes to Devise's sessions controller by
79 | # passing skip: :sessions to `devise_for` in your config/routes.rb
80 | config.skip_session_storage = [:http_auth]
81 |
82 | # By default, Devise cleans up the CSRF token on authentication to
83 | # avoid CSRF token fixation attacks. This means that, when using AJAX
84 | # requests for sign in and sign up, you need to get a new CSRF token
85 | # from the server. You can disable this option at your own risk.
86 | # config.clean_up_csrf_token_on_authentication = true
87 |
88 | # ==> Configuration for :database_authenticatable
89 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If
90 | # using other encryptors, it sets how many times you want the password re-encrypted.
91 | #
92 | # Limiting the stretches to just one in testing will increase the performance of
93 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
94 | # a value less than 10 in other environments. Note that, for bcrypt (the default
95 | # encryptor), the cost increases exponentially with the number of stretches (e.g.
96 | # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
97 | config.stretches = Rails.env.test? ? 1 : 10
98 |
99 | # Setup a pepper to generate the encrypted password.
100 | # config.pepper = '6ad7f5cc0cb4d2499518be8ae575f9e9deeccbd082d621f98684f9391b7b1864b39546af09db5007865deac386000e4e3bd5a85451f4263455be09b0af3fd5d8'
101 |
102 | # ==> Configuration for :confirmable
103 | # A period that the user is allowed to access the website even without
104 | # confirming their account. For instance, if set to 2.days, the user will be
105 | # able to access the website for two days without confirming their account,
106 | # access will be blocked just in the third day. Default is 0.days, meaning
107 | # the user cannot access the website without confirming their account.
108 | # config.allow_unconfirmed_access_for = 2.days
109 |
110 | # A period that the user is allowed to confirm their account before their
111 | # token becomes invalid. For example, if set to 3.days, the user can confirm
112 | # their account within 3 days after the mail was sent, but on the fourth day
113 | # their account can't be confirmed with the token any more.
114 | # Default is nil, meaning there is no restriction on how long a user can take
115 | # before confirming their account.
116 | # config.confirm_within = 3.days
117 |
118 | # If true, requires any email changes to be confirmed (exactly the same way as
119 | # initial account confirmation) to be applied. Requires additional unconfirmed_email
120 | # db field (see migrations). Until confirmed, new email is stored in
121 | # unconfirmed_email column, and copied to email column on successful confirmation.
122 | config.reconfirmable = true
123 |
124 | # Defines which key will be used when confirming an account
125 | # config.confirmation_keys = [ :email ]
126 |
127 | # ==> Configuration for :rememberable
128 | # The time the user will be remembered without asking for credentials again.
129 | # config.remember_for = 2.weeks
130 |
131 | # If true, extends the user's remember period when remembered via cookie.
132 | # config.extend_remember_period = false
133 |
134 | # Options to be passed to the created cookie. For instance, you can set
135 | # secure: true in order to force SSL only cookies.
136 | # config.rememberable_options = {}
137 |
138 | # ==> Configuration for :validatable
139 | # Range for password length.
140 | config.password_length = 8..128
141 |
142 | # Email regex used to validate email formats. It simply asserts that
143 | # one (and only one) @ exists in the given string. This is mainly
144 | # to give user feedback and not to assert the e-mail validity.
145 | # config.email_regexp = /\A[^@]+@[^@]+\z/
146 |
147 | # ==> Configuration for :timeoutable
148 | # The time you want to timeout the user session without activity. After this
149 | # time the user will be asked for credentials again. Default is 30 minutes.
150 | # config.timeout_in = 30.minutes
151 |
152 | # If true, expires auth token on session timeout.
153 | # config.expire_auth_token_on_timeout = false
154 |
155 | # ==> Configuration for :lockable
156 | # Defines which strategy will be used to lock an account.
157 | # :failed_attempts = Locks an account after a number of failed attempts to sign in.
158 | # :none = No lock strategy. You should handle locking by yourself.
159 | # config.lock_strategy = :failed_attempts
160 |
161 | # Defines which key will be used when locking and unlocking an account
162 | # config.unlock_keys = [ :email ]
163 |
164 | # Defines which strategy will be used to unlock an account.
165 | # :email = Sends an unlock link to the user email
166 | # :time = Re-enables login after a certain amount of time (see :unlock_in below)
167 | # :both = Enables both strategies
168 | # :none = No unlock strategy. You should handle unlocking by yourself.
169 | # config.unlock_strategy = :both
170 |
171 | # Number of authentication tries before locking an account if lock_strategy
172 | # is failed attempts.
173 | # config.maximum_attempts = 20
174 |
175 | # Time interval to unlock the account if :time is enabled as unlock_strategy.
176 | # config.unlock_in = 1.hour
177 |
178 | # Warn on the last attempt before the account is locked.
179 | # config.last_attempt_warning = false
180 |
181 | # ==> Configuration for :recoverable
182 | #
183 | # Defines which key will be used when recovering the password for an account
184 | # config.reset_password_keys = [ :email ]
185 |
186 | # Time interval you can reset your password with a reset password key.
187 | # Don't put a too small interval or your users won't have the time to
188 | # change their passwords.
189 | config.reset_password_within = 6.hours
190 |
191 | # ==> Configuration for :encryptable
192 | # Allow you to use another encryption algorithm besides bcrypt (default). You can use
193 | # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
194 | # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
195 | # and :restful_authentication_sha1 (then you should set stretches to 10, and copy
196 | # REST_AUTH_SITE_KEY to pepper).
197 | #
198 | # Require the `devise-encryptable` gem when using anything other than bcrypt
199 | # config.encryptor = :sha512
200 |
201 | # ==> Scopes configuration
202 | # Turn scoped views on. Before rendering "sessions/new", it will first check for
203 | # "users/sessions/new". It's turned off by default because it's slower if you
204 | # are using only default views.
205 | # config.scoped_views = false
206 |
207 | # Configure the default scope given to Warden. By default it's the first
208 | # devise role declared in your routes (usually :user).
209 | # config.default_scope = :user
210 |
211 | # Set this configuration to false if you want /users/sign_out to sign out
212 | # only the current scope. By default, Devise signs out all scopes.
213 | # config.sign_out_all_scopes = true
214 |
215 | # ==> Navigation configuration
216 | # Lists the formats that should be treated as navigational. Formats like
217 | # :html, should redirect to the sign in page when the user does not have
218 | # access, but formats like :xml or :json, should return 401.
219 | #
220 | # If you have any extra navigational formats, like :iphone or :mobile, you
221 | # should add them to the navigational formats lists.
222 | #
223 | # The "*/*" below is required to match Internet Explorer requests.
224 | # config.navigational_formats = ['*/*', :html]
225 |
226 | # The default HTTP method used to sign out a resource. Default is :delete.
227 | config.sign_out_via = :delete
228 |
229 | # ==> OmniAuth
230 | # Add a new OmniAuth provider. Check the wiki for more information on setting
231 | # up on your models and hooks.
232 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
233 |
234 | # ==> Warden configuration
235 | # If you want to use other strategies, that are not supported by Devise, or
236 | # change the failure app, you can configure them inside the config.warden block.
237 | #
238 | # config.warden do |manager|
239 | # manager.intercept_401 = false
240 | # manager.default_strategies(scope: :user).unshift :some_external_strategy
241 | # end
242 |
243 | # ==> Mountable engine configurations
244 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine
245 | # is mountable, there are some extra configurations to be taken into account.
246 | # The following options are available, assuming the engine is mounted as:
247 | #
248 | # mount MyEngine, at: '/my_engine'
249 | #
250 | # The router that invoked `devise_for`, in the example above, would be:
251 | # config.router_name = :my_engine
252 | #
253 | # When using omniauth, Devise cannot automatically set Omniauth path,
254 | # so you need to do it manually. For the users scope, it would be:
255 | # config.omniauth_path_prefix = '/my_engine/users/auth'
256 | end
257 |
--------------------------------------------------------------------------------