text
stringlengths
10
2.61M
require 'rails_helper' RSpec.describe UsersController, type: :controller do describe 'GET #new' do before { get :new } context 'when user tries to sign up' do it 'displays the sign up form' do expect(response).to render_template 'new' end it 'has the user instance variable set' do...
require "rails_helper" feature "Create a post" do scenario "Visitor creates a post" do visit new_post_path expect(page).to have_content("You need to sign in or sign up before continuing.") end end
require_relative 'api' require_relative '../models/track' module Spotify class << self attr_accessor :playlists, :tracks, :code, :token, :current_user, :client_id, :client_secret, :scope, :redirect_uri, :email, :password, :get_token_base_url def config yield self ...
class Account < ApplicationRecord has_many :digitalprints has_many :users, through: :digitalprints validates_presence_of :org_name, :website, :toll_free_number validates_uniqueness_of :org_name accepts_nested_attributes_for :digitalprints scope :org_name_search, -> (search) { where("org_name...
require_dependency "usermanagement/application_controller" module Usermanagement class PeopleController < ApplicationController before_action :authenticate_user! before_action :set_person, only: [:edit, :update] skip_around_action :scope_current_tenant # GET /people # def index # end #...
# frozen_string_literal: true require 'weese/requests' require 'weese/rail/urls' require 'weese/rail/station' require 'weese/rail/line' require 'weese/location' module Weese # Module containing everything MetroRail. Most important class: {MetroRail}. module Rail # MetroRail client. Used for accessing MetroRai...
class Category < ApplicationRecord validates :slug, uniqueness: true, presence: true before_validation :generate_slug has_many :categorydetails has_many :subcategories, through: :categorydetails has_many :themes has_many :dependencies has_many :codes has_many :graphics has_many :t3ds has_many :vid...
# Instructions: # Each with object works much like inject. Use each_with_object to return an array containing one reversed string for each string that has an even number of characters. # Code: def even_sum(arr) arr.each_with_object___ end even_sum(["cat", "dog", "bird", "fish"]) #=> ["drib", "hsif"]
class Servatron::Application def initialize root @root = Servatron::Path.new File.expand_path(root) end attr_reader :root # def start # Servatron::Server.new(self).start # end # def port # @port ||= options[:port] || 3000 # end # def app_root # @app_root ||= Servatron::Path.new(optio...
ActiveAdmin.register AnswerFollowup do permit_params :answer_id, question_ids: [] index do column :id column :question do |followup| q = followup.answer.question link_to q.to_s, admin_question_path(q) end column :answer column :following_questions do |followup| followup.quest...
class CaracteristicasComunesController < ApplicationController layout 'dashboard' def index @caracteristicas_comunes = CaracteristicaComun.all @tipos = @caracteristicas_comunes.group_by { |o| o.item.tipo }.values end def new @caracteristica_comun = CaracteristicaComun.new end def create # Instantia...
class AddProductCostIdToSaleCost < ActiveRecord::Migration def change add_column :sale_costs, :product_cost_id, :integer end end
class Product < ActiveRecord::Base belongs_to :product_family belongs_to :product_category belongs_to :product_length belongs_to :product_width belongs_to :product_thickness belongs_to :product_warranty belongs_to :color validates_presence_of :sku, :product_family_id, :product_length_id, ...
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib/', __FILE__) $:.unshift lib unless $:.include?(lib) require 'version' Gem::Specification.new do |s| s.name = 'angular_csrf' s.version = AngularCsrf::VERSION s.license = 'MIT' s.authors = ['Chaker Nakhli'] s.email = ['chaker.nakhli@sinbadsoft.com'] ...
class Class def attr_accessor_with_history(attr_name) attr_name = attr_name.to_s # make sure it's a string attr_reader attr_name # create the attribute's getter attr_reader attr_name+"_history" # create bar_history getter #your code here, use %Q for multiline strings...
class ApplicationController < ActionController::Base include Maestrano::Connector::Rails::SessionHelper protect_from_forgery with: :exception def authenticate_active_admin_user! authenticate_or_request_with_http_basic('Admin Connectors') do |username, password| ENV['ADMIN_USERNAME'].present? & ENV['AD...
# # sparkgui.rb, setup application framework, extended for gui-execution # $sparkFilename = "sparkgui.rb" $sparkPrefix = "("+$sparkFilename+") " # # define constants used to setup spark # # scene and server path $scenePath = '/usr/scene/' $serverPath = '/sys/server/' # (Input system) # # the default InputSystem use...
class AddTweetJsonToTweets < ActiveRecord::Migration def change add_column :tweets, :tweet_json, :text end end
module Panel class CommentsController < BaseController before_filter :authenticate_member! before_filter :set_entry layout 'panel' def index add_crumb @entry.name, panel_entry_path(@entry) end private def set_entry @entry = Entry.find(params[:entry_id]) end end end
require File.dirname(__FILE__) + '/../test_helper' class HelpTopicsControllerTest < ActionController::TestCase test "should show index page by default" do get 'index' assert_response :success assert_select 'h2', 'Welcome to TinyCI Help' end test "should show help topic" do get 'show', :id => 'te...
module Jelastic module REST module Control def attach_env_group(env_name:, env_group: nil, env_groups: nil) send_request( 'environment/control/rest/attachenvgroup', envName: env_name, envGroup: env_group, envGroups: env_groups ) end def create_environment(par...
require_relative "static_array" class DynamicArray attr_reader :length def initialize(capacity = 8) @store = StaticArray.new(capacity) @capacity = capacity @count = 0 @start_idx = 0 end # O(1) def [](index) if index >= @count raise "index out of bounds" return nil elsif ...
=begin Class Flash Gestion des messages @note En bas de module, on définit le singleton F. =end class Flash # ------------------------------------------------------------------- # Instance # ------------------------------------------------------------------- @messages = nil # Liste Array des m...
module Crud require 'bcrypt' puts "Module crud activated" # CREATE A HASH FOR USER PASSWORD def create_hash_digest(password) BCrypt::Password.create(password) end def verify_hash_digest(password) BCrypt::Password.new(password) end def create_secure_...
require_relative '../model/evento_diario' require_relative '../model/evento_semanal' require_relative '../model/evento_mensual' require_relative '../model/evento_anual' require_relative '../model/evento_no_recurrente' class EventoBuilder TipoEventos = Hash[ "diaria" => EventoDiario, "semanal" => EventoSeman...
# typed: true class CreateAppDetectionStrategies < ActiveRecord::Migration[6.0] def change create_table :app_detection_strategies do |t| t.references :app_detection, null: false, foreign_key: true t.text :implementation_in_ruby_dsl t.timestamps end end end
class SolutionsController < ApplicationController before_filter :authenticate_user! before_filter :load_problem, :only => [:new, :create] before_filter :load_solution, :except => [:new, :create] def new @solution = @problem.solutions.new @title = "New solution" end def create @solution = @prob...
require 'spec_helper' describe Spree::Feature do before(:each) do @feature = mock_model('Feature', headline1: "Spring Sale", headline2: 'On now') end context "validations" do it { should validate_presence_of(:headline1) } it { should validate_presence_of(:headline2) } end end
class UserRepService attr_reader :user def initialize(user) @user = user @config = user.user_config end def report user.entities.each do |entity| process_entity(entity) end end def process_entity(entity) # # binding.pry EntityRepService.new(entity, ...
require 'net/http' require 'uri' require 'json' require "openssl" require './key' def get_price uri = URI.parse("https://api.bitflyer.com") uri.path = '/v1/getboard' uri.query = '' https = Net::HTTP.new(uri.host, uri.port) https.use_ssl = true response = https.get uri.request_uri resp...
class LikesUser < ApplicationRecord belongs_to :liked_user, class_name: "User", foreign_key: :user_id belongs_to :likes_user, class_name: "User", foreign_key: :to_likes_user_id end
module Vcadmin class CampaignsController < Vcadmin::ApplicationController def index @campaigns = Campaign.all end def show @campaign = Campaign.find(params[:id]) @other_active_campaigns = Campaign.where.not(id: @campaign) end def new @campaign = Campaign.new end ...
class ApplicationController < ActionController::Base protect_from_forgery after_filter :flash_preserve protected def flash_preserve Rails.logger.info flash [:notice, :error, :alert].each do |key| cookies[key] = flash[key] unless flash[key].blank? end end def suggested_layout reques...
require 'test_helper' class ShipmentsControllerTest < ActionController::TestCase setup do @shipment = shipments(:one) sign_in users(:shipper) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:shipments) end test "should get new" do get :new ...
class TaskList < ActiveRecord::Base validates_presence_of :name end
module ShopifyImport module Creators module Adjustments class TaxCreator def initialize(shopify_tax_line, spree_order, spree_tax_rate) @shopify_tax_line = shopify_tax_line @spree_order = spree_order @spree_tax_rate = spree_tax_rate end def save! ...
class Application::Cell < Cell::Concept self_contained! include ::Cell::Slim include Sprockets::Rails::Helper # Sprockets::Rails::Helper's methods run in context of Cell::Concept and # looking for some variables which Cell::Concept doesn't provide. def self.assets_manifest Rails.application.assets_ma...
require File.dirname(__FILE__) + '/../routes' require 'rack/test' set :environment, :test describe 'The HelloWorld App' do include Rack::Test::Methods def app Sinatra::Application end context 'get "/Rush/Alfonso"' do before { get '/Rush/Alfonso' } specify { expect(last_response).to be_ok } s...
module OfxFileImporterService class << self def import_ofx_file(ofx_file, user) raise ArgumentError, "Usuário não informado" if user.nil? statement = OfxParserService.parse(ofx_file) return if already_exists_this statement import_statement(without_existing_transactions(statement), user) ...
module MedicalEntities class BloodCollectionFacilitiesController < ApplicationController before_action :set_blood_collection_facility, only: %i[show edit update destroy] # GET /medical_entities/blood_collection_facilities # GET /medical_entities/blood_collection_facilities.json def index @blood...
name 'habitat' maintainer 'Chef Software, Inc.' maintainer_email 'cookbooks@chef.io' license 'Apache-2.0' description 'Habitat related cookbooks for chef-client' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.27.0' %w(ubuntu debian redhat centos suse scientific oracle amazon opensu...
require "application_system_test_case" class Intervention3sTest < ApplicationSystemTestCase setup do @intervention3 = intervention3s(:one) end test "visiting the index" do visit intervention3s_url assert_selector "h1", text: "Intervention3s" end test "creating a Intervention3" do visit inte...
namespace :fedena_theme do desc "Install Fedena Theming Module" task :install do system "rsync --exclude=.svn -ruv vendor/plugins/fedena_theme/public ." Rake::Task["css_themes:generate_color_css"].execute Rake::Task["css_themes:generate_font_css"].execute end end namespace :css_themes do desc "Creat...
require 'rails_helper' RSpec.describe Event, type: :model do before(:each) do @venue1 = Venue.create!(name: "Da lat") @category1 = Category.create!(name: "Entertainment") @event1 = Event.create!(name: "Event 1", extended_html_description: "<p>this is a test event</p>", venue: @venue1, category: @categor...
class RenameeUserColumns < ActiveRecord::Migration[6.0] def change rename_column :users, :profile_picture_google, :picture_google rename_column :users, :profile_picture_local, :picture_local end end
Given(/^I am on collage display page$/) do visit "http:localhost:8080/Mosaicss/login.jsp" fill_in('username', :with => 'test') fill_in('password', :with=> 'test') click_button("Login") end Then(/^the page should have a div "collage" section/) do expect(find_by_id('collage-div')['innerHTML']=="Collage") end The...
module OperaWatir # @private VERSION = File.read(File.join(File.dirname(__FILE__), '../..', 'VERSION')).strip.freeze # Fetches OperaWatir's version number. Note that this is not the # same as OperaDriver's version number. # # @return [String] current version of OperaWatir def self.version VERSION ...
class Users::RegistrationsController < Devise::RegistrationsController before_filter :configure_permitted_parameters def create build_resource(sign_up_params) if resource.class == StadiumUser resource.build_stadium sign_up_params[:stadium_attributes] end resource.save if resource.persist...
class VehiclesController < ApplicationController def index @user = current_user @vehicles = @user.vehicles.all respond_to do |format| format.html # index.html.erb format.json { render json: @vehicles } end end def show @vehicle = current_user.vehicles.find(params[:id]) ...
require 'rails_helper' RSpec.feature 'Authentication', type: :feature do # rubocop: disable Metrics/BlockLength before :each do user = User.new(name: 'Ezekiel', username: 'ezeko') user.save end describe 'Sign up process' do scenario 'User can sign up successfully' do visit '/sign_up' fil...
require 'spec_helper' describe GitSnatch::Grab do let(:instance) { described_class.new(repo, sha, location) } let(:repo) { 'random_project' } let(:sha) { '214e301aef' } let(:location) { 'readme.md' } describe '#content' do subject { instance.content } let(:body) { 'Test Response' } let(:request...
class CodeExamplesController < ApplicationController before_action :set_code_example, only: [:show, :edit, :update, :destroy] # GET /code_examples # GET /code_examples.json def index @code_examples = CodeExample.all end # GET /code_examples/1 # GET /code_examples/1.json def show render :layout...
#!/usr/bin/env ruby # (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> # Write properties of document in a Plan R repository to STDOUT require 'plan-r/application/cli' require 'plan-r/repo' class App < PlanR::CliApplication def self.disable_plugins?; true; end def self.disable_jruby?; true; end def...
## # = 記事モデル # class Article < ActiveRecord::Base has_many :comments acts_as_taggable validates :title, presence: true validates :body, presence: true scope :top_ten, -> { order(arel_table[:pv].desc).limit(10) } def read! self.pv += 1 self.save! self end end
# frozen_string_literal: true module GraphQL module Tracing module PrometheusTrace include PlatformTrace def initialize(client: PrometheusExporter::Client.default, keys_whitelist: ["execute_field", "execute_field_lazy"], collector_type: "graphql", **rest) @client = client @keys_white...
require 'mailgun' require "mailgun/exceptions/exceptions" module Mailgun # A Mailgun::Events object makes it really simple to consume # Mailgun's events from the Events endpoint. # # # See the Github documentation for full examples. class Events def initialize(client, domain) @client = client...
class DesktopController < ApplicationController layout 'desktop' include Apotomo::ControllerMethods def index use_widgets do |root| # statically define list of widgets to display: root << cell(:weather, :display, 'weather_forecast') root << cell(:michal, :sobe...
class Admin < ApplicationRecord belongs_to :user def classify (option) case option[:search_by] when 'user' if option.has_key?(:user) value = option['user'] if User.where(username: value).exists? @user= User.find_by(username: valu...
require 'rails_helper' RSpec.describe CaseNumberValidator do let(:model_class) do Class.new do include ActiveModel::Model attr_accessor :case_number def self.name 'MyModel' end validates :case_number, case_number: true end end it 'will validate a string containing...
# == Schema Information # # Table name: leagues # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # name :string # user_id :integer # meeting :integer # join_code :integer # steward :integer # class League < Ac...
class Series < ActiveRecord::Base has_many :game_series has_many :games, :through => :game_series validates_length_of :name, :in => 2..128 def to_display_name name end def to_param "#{id}-#{name.gsub(/[^\w]/, '-')}" end end
class Students::ApplicationController < ApplicationController before_filter :require_student layout "students" end
require 'rails_helper' describe 'SpecimenMessageProcessor' do let(:blood_good_message) do { "header" => { "msg_guid" => "ab6d8d37-caf2-4dbb-a360-0032c7a7a76c", "msg_dttm" => "2016-04-25T18:42:13+00:00" }, "specimen_received" => { "patient_id" => "89456...
# encoding: UTF-8 # frozen_string_literal: true require 'spec_helper' describe 'analytics code snipets' do before(:each) do @site = Factory(:site, domain: '127.0.0.1.xip.io') end describe 'gauge', js: true do it 'generate gauge snippet if site exists' do Monologue::Config.gauge_analytics_site_id = ...
require 'spec_helper' describe BencodingDecoder do let(:decoder) {BencodingDecoder.new} subject { decoder } it 'should decode int' do expect(decoder.decode 'i123e').to eq(123) end it 'should decode negative int' do expect(decoder.decode 'i-1734e').to eq(-1734) end it 'should decode string' do expect(...
class MilestonesController < ApplicationController include Concerns::Projected # GET /:token/milestones def index @milestones = Milestone.where(project_id: current_project.id) end end
require 'ovto' class MyApp < Ovto::App class State < Ovto::State item :board, default: [ [nil, nil, nil], [nil, nil, nil], [nil, nil, nil], ] item :player, default: 0 def game_over? return true if winner return true if board.all?{|row| row.all?{|cell| cell } } ret...
module Mirren module Rigs class Price < BaseStruct attribute :currency, Types::String attribute :price, Types::FloatString attribute :hour, Types::FloatString attribute :minhrs, Types::FloatString attribute :maxhrs, Types::FloatString attribute :enabled, Types::Bool end e...
class AddAvatarColumnsToResources < ActiveRecord::Migration def change add_attachment :resources, :avatar end end
require 'rails_helper' RSpec.describe BooksController do before(:each) do user = FactoryGirl.create(:user) sign_in user end let(:book) { FactoryGirl.create(:book) } let(:author) { FactoryGirl.create(:author) } describe 'GET index' do context 'there are books' do it 'populates an array of b...
class CreateContentItems < ActiveRecord::Migration def change create_table :content_items do |t| # Universal columns t.string :title t.integer :author_id t.integer :category_id # Article columns t.text :body # Link columns t.text :intro ...
namespace :mamashai do desc "一次性更新全文检索索引" task :update_full_text => [:environment] do log = Logger.new('full.log') for post in Post.find(:all) content_ = RMMSeg::segment(post.content).join(' ') post.update_attribute(:content_, content_) log.info "#{post.id} \n" #post.make_rmmseg ...
class CreateSubscriptions < ActiveRecord::Migration[5.0] def change create_table :subscriptions do |t| t.string :SubContractNumber t.date :SubExpireDate t.string :SubNotes t.boolean :SubActive t.string :SubSeatCount t.timestamps end end end
require 'openssl' # frozen_string_literal: true # Generates unique keys class KeyGenerator ADDRESS_VERSION = "00" attr_reader :key_pair, :private_key_hex, :public_key_hex, :private_key, :public_key def initialize elliptic_curve = OpenSSL::PKey::EC.new("secp256k1") @key_pair = elliptic_curve.generate_ke...
require 'minitest/autorun' require_relative 'cash_register' require_relative 'transaction' require 'stringio' class TransactionTest < Minitest::Test def setup @register = CashRegister.new(500) @transaction = Transaction.new(500) end def test_prompt_for_payment input = StringIO.new('500\n') assert_outp...
require "spec_helper" describe TeacherDetailsController do describe "routing" do it "routes to #index" do get("/teacher_details").should route_to("teacher_details#index") end it "routes to #new" do get("/teacher_details/new").should route_to("teacher_details#new") end ...
# encoding: utf-8 require 'test_helper' module Nls module EndpointInterpret class TestWarning < NlsTestCommon def setup super Nls.remove_all_packages Interpretation.default_locale = nil end def test_missing_package_warning missing_package = Package.new("...
require 'emailage' # http://oauth.net/core/1.0/#sig_base_example describe Emailage::Signature do let(:method) {'GET'} let(:url) {'http://photos.example.net/photos'} let(:params) {{ oauth_consumer_key: 'dpf43f3p2l4k3l03', oauth_token: 'nnch734d00sl2jdk', oauth_signature_method: 'HMAC-SHA1', oauth_...
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/people/index.json.rb" do include PeopleHelper before do person = stub_model(Person, :id => 1, :firstname => 'Clint', :lastname => 'Easterbunny', :date_of_birth => '2008-03-23', :serial_number => 1, :duplicate_count ...
class ThermostatAPI < Sinatra::Base MAX_TEMP_PSM = 25 MAX_TEMP = 32 MIN_TEMP = 10 before do response.headers['Access-Control-Allow-Origin'] = '*' end def power_save_mode? thermostat = Thermostat.get(@thermostat.id) thermostat.power_save_mode end def get_current_temperature thermostat...
class Category < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged default_scope { order('index ASC NULLS LAST') } scope :main_categories, -> { where("parent_id is null") } mount_uploader :image, CategoryImageUploader validates_uniqueness_of :name validates_presence_of :name bel...
module Api module V1 class BoardController < ApplicationController def index data = [{id: 0, text: "hoge"}, {id: 1, text: "fuga"}, {id: 2, text: "piyo"}, {id: 3, text: "meta"}] render json: { status: 'SUCCESS', board_data: data} end def card_data board_cards = BoardCard....
require 'rails_helper' describe Message do let(:message) { build(:message) } it 'has a valid factory' do expect(message.valid?).to be true end describe 'validates' do it { is_expected.to validate_presence_of :email } it { is_expected.to validate_presence_of :name } it { is_expected.to valida...
require 'spec_helper' describe Api::V4::OrdersController, type: :controller do let!(:item) { FactoryGirl.create(:item_with_specs_and_photos) } let!(:spec) { item.specs.first } let!(:store_delivery_type) { "store_delivery" } let!(:home_delivery_type) { "home_delivery" } let!(:home_delivery_by_credit_card_type...
class CreateSprintPlannings < ActiveRecord::Migration def change create_table :sprint_plannings do |t| t.string :active t.date :start_date t.date :end_date t.string :sprint_name t.string :sprint_desc t.integer :sprint_status_id t.integer :project_master_id t.integer...
class Color < ActiveRecord::Base belongs_to :color_palette belongs_to :color_family has_many :products validates_presence_of :color_palette_id, :color_family_id, :color_number, :name validates_uniqueness_of :color_number def image case color_palette.name.downcase when "stone" "...
require "test_helper" class UserTest < ActiveSupport::TestCase def setup @user = User.create(name: 'Sam Smith', email: 'sam@example.com', password: 'welcome', password_confirmation: 'welcome') end def test_user_should_be_not_be_valid...
class CreateComments < ActiveRecord::Migration[5.0] def change create_table :comments do |t| t.text :message t.boolean :status t.references :post, foreign_key: true t.references :visitor, foreign_key: true t.timestamps end end end
class Team def initialize(name, level, team_member_names) @name = name @level = level @members = team_member_names @points = 0 end def to_hash hash = {} hash[:team_name] = @name hash[:level] = @level hash[:points] = @points return hash end end
# frozen_string_literal: true require 'simplecov' require 'active_support/core_ext/numeric/time' module SimpleCovEnv module_function def start! return unless ENV['CI'] configure_profile SimpleCov.start SimpleCov.minimum_coverage 100 end def configure_profile SimpleCov.configure do ...
# coding: utf-8 # All tests for /Users/tamc/Documents/github/excel_to_code/spec/test_data/ExampleSpreadsheet.xlsx require 'test/unit' require_relative 'examplespreadsheet' class TestExampleSpreadsheet < Test::Unit::TestCase def worksheet; @worksheet ||= ExampleSpreadsheet.new; end def test_formulaetypes_a1; assert...
require 'spec_helper' describe "mobiles/index.html.haml" do before(:each) do assign(:mobiles, [ stub_model(Mobile), stub_model(Mobile) ]) end it "renders a list of mobiles" do render end end
require 'puma/capistrano' require 'bundler/capistrano' set :application, "tw_asset_manager" set :repository, "https://github.com/TWChennai/assets_manager.git" # set :scm, :git # You can set :scm explicitly or Capistrano will make an intelligent guess based on known version control directory names # Or: `accurev`, `b...
class Restaurant < ActiveRecord::Base belongs_to :category has_many :reviews validates :name, uniqueness: true, presence: true validates :address, presence: true validates :city, presence: true validates :state, presence: true validates :zip_code, presence: true end
class AddMediumToQuestion < ActiveRecord::Migration def change add_reference :questions, :medium, index: true end end
class HomeController < ApplicationController before_filter :authenticate def index @slug = 'home' #figure out the next item in the play cycle @next_key = get_next_key(@slug) end def pod @slug = params[:slug] @pod = Settings.pods[@slug] if Settings.loop.enabled == true @p...
require 'test_helper' class IdeasControllerTest < ActionController::TestCase setup do @idea = ideas(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:ideas) end test "should get new" do get :new assert_response :success end test "s...
require 'ice_nine' require 'value_object' class TransportLeg < ValueObject attr_reader :departure_location attr_reader :arrival_location def initialize(departure_location, arrival_location) # TODO Check valid values @departure_location = departure_location @arrival_location = arrival_location ...
module Slugifiable module InstanceMethods def slug self.username.split(' ').join('-') end end module ClassMethods def find_by_slug(slug) username = slug.gsub('-',' ') all.find_by(username: username) end end end
class Admin::ProjectsController < ApplicationController before_action :authenticate_user! before_action :set_project, only: [:show, :edit, :update, :destroy] layout "admin" # GET /admin/projects def index @projects = Project.all end # GET /admin/projects/1 def show redirect_to edit_admin_proj...