text
stringlengths
10
2.61M
class CreateCreditCashingApplications < ActiveRecord::Migration def change create_table :credit_cashing_applications do |t| t.string :bankcard t.string :real_name t.integer :amount t.integer :status t.string :comment t.references :user t.timestamps end end end
class CreateRatingListRatingCriteria < ActiveRecord::Migration[5.2] def change create_table :rating_list_rating_criteria do |t| t.belongs_to :rating_list, foreign_key: true t.belongs_to :rating_criterium, foreign_key: true t.timestamps end end end
Gem::Specification.new do |s| s.name = 'userl' s.version = '0.1.1' s.date = '2012-10-01' s.summary = "A CLI to get the most used languages of a GitHub user" s.description = "A CLI to get the most used languages of a GitHub user" s.authors = ["Marco Sero"] s.email = 'marco@m...
require 'garage' describe Garage do let!(:working_bike) { double :bike, :working? => true } let!(:broken_bike) { double :bike, :working? => false, :fixing => 'fixed_bike' } describe '#broken_storage' do it "contains all the broken bikes delivered by the van" do expect(subject.broken_storage).to be...
class HomeController < ApplicationController # caches_action :app, cache_path: :action_cache_key, # unless: -> {Rails.env.development?} # quicker first rendering (pick-up ready page from cache) - Dramatic effect. Must be skipped in development before_action :set_http_cache_headers, if: "Rai...
require "spec_helper" module TephueMemoryRepo class TestAdapter < Adapter attr_reader :next_id end describe Adapter do let(:tag) { :things } let(:unsaved_entity) { {id: nil, foo: "foo", two: 2} } let!(:repo) { TestAdapter.new } let!(:saved_entity) { {id: repo.next_id, foo: "foo", two: 2}...
class SessionsController < ApplicationController before_action :check_params, only: [:create] before_action :signed_in?, only: [:new, :create] def new @user = User.new end def create_from_socialmedia user = User.from_omniauth(request.env["omniauth.auth"]) session[:user_id] = user.id redirect...
require "mpex/version" require "mpex/http" require "mpex/mpex" require "mpex/converter" module Mpex def self.version_information "MPEx commandline interface #{VERSION} (c) 2013 Fa Wuxi" end end
require 'spec_helper' require 'awesome_print' describe Defaultable::Registry do before(:each) do class DummySetting < Defaultable::Settings; end end after(:each) do DummySetting.set_defaults Hash.new end it "should log settings to the registry." do setting = DummySetting.new setting.blah = 'asdf' set...
######################################### # This class provide methods to install databases ######################################### require 'databases_support_install_checker.rb' class DatabasesSupportInstall < DatabasesSupport attr_accessor :installed_databases def initialize(info) #RETRIEVE REPOSITORY I...
#encoding: UTF-8 require 'spec_helper' describe Termit::DataFetcher do describe "data method" do let(:url) { "http://translate.google.com/?tl=fr&sl=en&ie=UTF-8&oe=UTF-8" } let(:text) { "it would require two large integer variables to store her weight, else she would cause a buffer overflow." } it "should...
Iyyov.context do |c| hostname = `hostname -s`.strip RJack::SLF4J[ File.basename( __FILE__ ) ].info( "Setup services for [#{hostname}]." ) case hostname when /^server-[012]$/ c.define_daemon { |d| d.name = "widget-factory" } when 'server-3' c.define_daemon { |d| d.name = "assembly-line" } end en...
require 'pry' def build_matrix(filename) matrix = {} File.open(filename).readlines.each_with_index do |line, x| line.strip.split('').each_with_index do |dot, y| matrix[x] ||= {} matrix[x][y] = dot end end matrix end def print_matrix(matrix) ...
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # # a2 + b2 = c2 # # For example, (3x3) + (4x4) = 9 + 16 = 25 = (5x5). # # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def is_whole? n n.to_i == n end # Math.sqrt(n) def generate...
# encode: utf-8 # # Урок__ 14__ — игра Виселица ver 0.3 # Задача 15-4 — Регистронезависимая виселица ver 0.4 # Задача 19-3 — Виселица с обработкой исключений # Задача 23-6 — Виселица в github # Задача 53-2 — Gemfile в виселице class WordReader def read_from_file(file_name) begin f = File.new(file_name,"r:U...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
class Weapon < Item attr_reader :damage def initialize(name, weight, damage) super(name, weight) @damage = damage end def hit(robot, amount=45) robot.wound(amount) end end
class RemoveGenreNameFromItems < ActiveRecord::Migration[5.2] def change remove_column :items,:genre end end
class SessionsController < ApplicationController def new end def create # controller on form post user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in user # this is defined in the sessions helper redirect_to user # go ...
class AccountsController < ApplicationController # アカウントを削除した場合に削除完了ページに飛べないため追加 skip_before_action :require_login, raise: false, only: %i[delete_completed] def show; end def destroy @user = User.find(current_user.id) @user.destroy session[:user_id] = nil redirect_to account_delete_completed_p...
require 'spec_helper' describe HomeController do def mock_feed(stubs={}) (@mock_feed ||= mock_model(Feed).as_null_object).tap do |feed| feed.stub(stubs) unless stubs.empty? end end describe "GET 'index'" do it "should be successful" do get 'index' response.should be_success en...
class AddUniqIndexForAppointment < ActiveRecord::Migration[5.0] def change attrs_batch = Appointment.where.not(status: ['free', 'cancel_client', 'cancel_owner']) .group(:start, :showing_time, :status, :worker_id, :organization_id).count .find_all{|x, y| y > 1} attrs_batch.each do |attrs, count| ...
class UserMailer < ActionMailer::Base add_template_helper( ApplicationHelper ) default from: "Fanzo <notifications@fanzo.me>", css: :email def new_fanzone_post( aPostId ) @post = Post.includes(:user, :tailgate => :user).find_by_id(aPostId) if @post theSubject = "#{@post.user.full_name} just pos...
pg_ver = input('pg_version') pg_dba = input('pg_dba') pg_dba_password = input('pg_dba_password') pg_db = input('pg_db') pg_host = input('pg_host') pg_log_dir = input('pg_log_dir') pg_audit_log_dir = input('pg_audit_log_dir') control "V-72929" do title "PostgreSQL must generate audit records when privileges/per...
class Sale < ActiveRecord::Base before_create :populate_guid belongs_to :book private def populate_guid self.guid = SecureRandom.uuid() end end
require_relative 'piece' require 'colorize' #try to make a move, then raise an error if there is a problem #catch the error in the game class class Board GRID_SIZE = 8 def initialize(grid = nil) @grid = (grid.nil? ? new_board : grid) end def self.on_board?(col, row) col.between?(0, GRID_SIZE-1) && ro...
class Controller def initialize(args={}) @view = args.fetch(:view, View) @filepath = args.fetch(:filepath, 'db/shmikea.csv') @model = args.fetch(:model, Shmikea.new(@filepath)) search_bot(ARGV[0]) end def search_bot(user_input) case user_input when 'search' @view.display_catalogue(@...
class ChangeDateFormatInTrucks < ActiveRecord::Migration[5.0] def change change_column :trucks, :day_off, :string change_column :trucks, :day_start, :string end end
FactoryGirl.define do factory :auction do title { Faker::Lorem.word} details { Faker::Lorem.sentence } current_price { 0 } ends_on{ Faker::Date.forward(23)} reserve_price { Faker::Number.decimal(2)} end end
class AddLinksToProjects < ActiveRecord::Migration def change add_column :projects, :link, :string end end
require 'pry' class Day03 attr_accessor :map, :map_width, :pos_x, :pos_y TREE = '#' def initialize @map = File.readlines('../input.txt') end def count_trees(slope) (x, y) = slope self.reset self.move(x, y, 0) end private def reset @map_width = map[0].size - 1 @pos_x = 0 ...
class Video < ApplicationRecord has_attached_file :media, styles: { mp4_360hd: { geometry: "640x360", format: 'mp4' }, thumb: { geometry: "854x480#", format: 'jpg', time: 10 } }, processors: [:transcoder] validates_attachment_content_type :media, :content_type => /\Avideo\/.*\Z/ en...
# # Cookbook Name:: et_secrets # Resource:: replace_vault_token # # Copyright (c) 2016 EverTrue, All Rights Reserved. resource_name :replace_vault_token default_action :renew property :token_name, kind_of: String, name_attribute: true # A full URL is expected for the vault host. # E.g. # http://localhos...
require 'rails_helper' RSpec.describe Admin::AccessController, type: :controller do describe "#index" do it "gets new pref if none exists" do get :index expect(assigns[:preference].persisted?).to eq true end it "gets existing pref if exists" do pref = Preference.create(allow_create_so...
class Villain < ActiveRecord::Base #order villains on home page by name default_scope :order => 'name' #prevent removal of products that are referenced by line items has_many :line_items has_many :orders, :through => :line_items before_destroy :ensure_not_referenced_by_any_line_item #validation that name and ge...
require_relative 'logic' # Player class. class Player attr_reader :y, :x1, :y1, :size attr_writer :ground_level, :left_forbidden, :right_forbidden attr_accessor :x, :is_jumping, :is_falling, :speed_x def initialize(x = 0, y = 0) @x = x @y = y @ground_level = 670 @size = 50 # Width and height. ...
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable #a user must always have ...
require 'test_helper' class TweetTest < ActiveSupport::TestCase setup do @default_attributes = {:user_id => users(:one).id, :content => "Hello World!"} end test "should not save emtpy tweet" do tweet = Tweet.new(@default_attributes.merge(:content => nil)) assert !tweet.valid? assert tweet.e...
# Write a program that: # # Asks the user to enter a word. # The program should print each letter in the word the number of times it appears in the word. p "Enter a word:" word = gets.chomp word = word.upcase.split("") word.each do |the_character| p the_character.downcase+" appears "+word.count(the_character).to...
require 'user' class SwankLog < ActiveRecord::Base def self.log(code, message) sl = SwankLog.new sl.code = code sl.message = message.to_json sl.save && sl.reload end def self.codes all(:group => :code).map {|l| l.code}.sort end end
require 'telegram/bot' class CallMeController < ApplicationController skip_before_action :verify_authenticity_token before_action :check_json! def call_me text = "Оставлена заявка на сайте\nИмя: #{@json['name']}\nНомер телефона: #{@json['phone']}\nКомментарий: #{@json['comment']}" Telegram::Bot::Clien...
class CreateCharacters < ActiveRecord::Migration[4.2] def change create_table :characters do |t| t.string :name t.string :gender t.string :age t.integer :film_id t.integer :species_id t.timestamp end end end
require 'json' namespace :quotes do desc "Import quotes from json file" task import: :environment do path = Rails.root + "db/quotes.json" file = File.open(path, 'r') hash = JSON.parse(file.read) hash.each do |quote| Quote.create (quote) end end end
# frozen_string_literal: true require 'minitest/autorun' require 'minitest/emoji' require './lib/board' require './lib/player' class PlayerTest < Minitest::Test def test_it_exists player = Player.new assert_instance_of Player, player end def test_it_is_anonymous_to_begin player = Player.new a...
require "docker-api" require "sinatra" require "dotenv" require "omniauth-twitter" require "twitter" require "json" def empty(str) case str.empty? when true return [] else return str.split(/\s*,\s*/) end end # Loading env Dotenv.load if ENV["TWITTER_CONSUMER_KEY"] == "" || ENV["TWITTER_CONSU...
class TipoDocumento < ActiveRecord::Base has_many :quejas attr_accessible :descripcion, :sigla validates_presence_of :descripcion validates_presence_of :sigla #buscador def self.search(search) where('sigla like ? or descripcion like ?', "%#{search}%", "%#{search}%" ) end end
require 'spec_helper' describe 'fmw_domain::extension_soa_suite', :type => :class do describe 'unix 1036' do let :pre_condition do " class { 'fmw_jdk::install': java_home_dir => '/usr/java/jdk1.7.0_75', source_file => '/software/jdk-7u75-linux-x64.tar.gz', } ...
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel...
class Tweet < ActiveRecord::Base validates_presence_of :text validates_presence_of :from_user validates_presence_of :source validates_presence_of :status_id validates_presence_of :tweeted_at validates_uniqueness_of :status_id, :message => 'Twitter status_id id has already been taken', :if => :status_id? v...
module ApplicationHelper def fckeditor( object, method, fck_options = { }, options = { } ) # setup fck_options to be passed to js constructor width = fck_options[:width] || 'null' height = fck_options[:height] || 'null' toolbarSet = fck_options[:toolbarSet] || Fckeditor.config[:toolbar_set] || 'Default' valu...
require 'van' require 'docking_station' describe Van do it 'has a default capacity' do end it { is_expected.to respond_to(:load).with(1).argument } describe 'dockingstation interactions' it 'is able to call release_bike method on dockingstation' do station = DockingStation.new bikebroken = B...
require 'user_agent' module Browser extend ActiveSupport::Concern included do helper_method :current_browser end def current_browser @current_browser ||= Browser::Base.new( request ) end class Base INQUIRY = /^[a-z_]+\?$/ def initialize( request ) @ua = UserAgent.parse( request.e...
require 'github_rb/commands/config' RSpec.describe GithubRb::Commands::Config do it "executes `config` command successfully" do output = StringIO.new github_api_key = nil options = {} command = GithubRb::Commands::Config.new(github_api_key, options) command.execute(output: output) expect(ou...
class CreatePersonals < ActiveRecord::Migration def change create_table :personals do |t| t.string :title t.text :description t.integer :rang t.string :image_url t.string :status, default: "Показать" t.timestamps null: false end end end
class AddIndexOnMarkedAttendanceRecord < ActiveRecord::Migration def self.up add_index :marked_attendance_records, :attendance_type, :name => "index_by_attendance_type" end def self.down remove_index :marked_attendance_records, :name => "index_by_attendance_type" end end
class AddLatLongToNotes < ActiveRecord::Migration def change add_column :notes, :latitude, :integer add_column :notes, :longitude, :integer end end
Bitcoin.require_dependency :sequel, message: "Note: You will also need an adapter for your database like sqlite3, mysql2, postgresql" require 'bitcoin/storage/sequel_store/sequel_migrations' module Bitcoin::Storage::Backends # Storage backend using Sequel to connect to arbitrary SQL databases. # Inherits from S...
require_relative "./resource" require_relative "./metadata" # Wrapper for {https://m2x.att.com/developer/documentation/v2/distribution M2X Distribution} API class M2X::Client::Distribution < M2X::Client::Resource include M2X::Client::Metadata PATH = "/distributions" class << self # # Method for {https:...
#============================================================================== # Bravo Checkpoint System #------------------------------------------------------------------------------ # Author: Bravo2Kilo # Version: 1.0a # # Version History: # v1.0 = Initial Release # v1.0a = Fixed a bug #========================...
# frozen_string_literal: true RSpec.describe 'User Attendance Logs Request', type: :request do include_context 'with branch location' include_context 'with user token' include_context 'with json response' include_context 'with event' let(:attendee) { build(:event_attendee) } let(:user) { user_regular } ...
require 'spec_helper' require 'dollar_word' describe DollarWord do it 'returns default of 0 for no options given' do expect(DollarWord.compute({}).size).to eq(0) end context 'returns a correct word count' do it '0 words' do compute = DollarWord.compute({words: ''}) expect(compute[:word_coun...
# ReceiptPrinter configuration class class ReceiptPrinter attr_accessor :receipt_printer_type,:receipt_printer_header_height,:receipt_printer_header_type,:receipt_printer_template RECEIPT_PRINTER_TYPES ={ 0=> "Normal", 1=> "Dot Matrix", 2=> "Thermal", } RECEIPT_PRINTER_TEMPLATES = { 0 => "A4", ...
class HomeController < ApplicationController def index @song_count = Song.all.count end end
class Search < ApplicationRecord def events @events ||= find_events end private def find_events spots = Spot.order(:city) spots = spots.where("city like ?", "%#{city}%") if city.present? events = Event.all events = events.joins("JOIN spots ON events.spot_id = spots.id") return events ...
# encoding: UTF-8 require 'spec_helper' describe 'Sessions' do let :admin do Admin.sham! end let :invalid_admin do mock :admin, { :username => "invalid_username", :password => "s" } end context "User logs in" do it 'succesfully' do log_in admin page.should have_content 'Zalogowano pom...
require File.dirname(__FILE__) + '/../../test_helper' class TinyCI::OutputTest < ActiveSupport::TestCase test "should be empty if input string is empty" do assert TinyCI::Output.new("").empty? end test "should parse output" do output = TinyCI::Output.new("1,cmd,some output\n2,cmd,more output") lin...
require 'spec_helper' describe Banker::CreditExpertUK do let(:support_files) {File.expand_path('../../support/credit_expert_uk/',__FILE__)} let(:mcclogin) { File.read( File.expand_path('MCCLogin.aspx.html', support_files) ) } let(:mcclogin_memorable_word) { File.read( File.expand_path...
class PostsController < ApplicationController before_action :authenticate_user! before_action :find_post, :only => [:show, :edit, :update] def index #redirect_to tab self-selected by user as primary interest. end def show end def new @post = Post.new end # "post"=>{"content"=>"", "user_i...
class InquiriesController < ApplicationController wrap_parameters :inquiry, include: ["question"] # before_action :get_inquiry, only: [:show, :update, :destroy] before_action :set_inquiry, only: [:update, :destroy] before_action :get_inquiry, only: [:index, :show] before_action :authenticate_user!, only: [:c...
class SessionsController < ApplicationController skip_before_action :authorized, only: [:new, :create] def new @cellblocks = CellBlock.all @latest_incident_reports = IncidentReport.latest_incident_reports @latest_prisoners = Prisoner.latest_prisoners end def create @guard = Guard.find_by(email...
module PdfTempura class Document class << self def template_file_path @template_file_path end def template(path) raise ArgumentError, "Template path must be a string." unless path.is_a?(String) @template_file_path = path end def pages @pages ||= []...
require 'csv' require 'English' require_relative 'helpers/constants' require_relative 'helpers/validators' require_relative 'helpers/menu' require_relative 'base_menu/selection_menu' require_relative 'base_menu/list_menu' require_relative 'types/record' require_relative 'event_menu' class Core def initialize @re...
class Luhn INITIAL_TOTAL = 0 def initialize(number) @number = number end def addends self.class.construct_luhn(@number, "new") end def checksum self.class.sum(addends, INITIAL_TOTAL) end def valid? checksum % 10 == 0 end def self.create(number) check_sum = sum(construct_lu...
class Backend::ApplicationController < ApplicationController skip_before_action :authenticate_user! before_action :authenticate_admin! protected def authenticate_admin! unless (user_signed_in? && current_user.admin?) if user_signed_in? flash[:alert] = t('controllers.backend.applicat...
class RemoveSubAndConfirmedFromSendees < ActiveRecord::Migration[5.1] def change remove_column :sendees, :sub remove_column :sendees, :confirmed end end
# encoding: UTF-8 class Library def self.query opts res=['Multimedia','SupportingCourse','LearningDynamic'] if opts['resource']>=1 and opts['resource'] <=3 res=[res[opts['resource']-1]] end main( opts['q'].nil? ? nil : clean_query_term(opts['q']), opts['owner'], opts['sort'...
class AddIndustryColumnToExperience < ActiveRecord::Migration def change remove_column :experiences, :industry add_column :experiences, :industry_id, :integer end end
require 'spec_helper' describe 'Trade Leads API V1', type: :request do before(:all) do TradeLead::Australia.recreate_index TradeLead::Canada.recreate_index TradeLead::Fbopen.recreate_index TradeLead::State.recreate_index TradeLead::Uk.recreate_index TradeLead::Mca.recreate_index TradeLead...
class ComplaintChatsController < ApplicationController before_action :set_complaint_chat, only: [:show, :update, :destroy] def create_chat complaint_chat = ComplaintChat.new(chats: params[:chats], role: params[:role], image: params[:image], ...
require 'rubygems' require 'open-uri' require 'nokogiri' class Unhyperbole attr_accessor :content def initialize(raw_content) self.content = get_cleaned_content(raw_content) end def get_cleaned_content(raw_content) # Crudely strip out module-crunchbase onwards, because the # content isn't nested...
INITIAL_MARKER = ' ' P_ONE_MARKER = "X" P_TWO_MARKER = "O" WINNING_SCORE = 5 WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [7, 5, 3]] WINNING_SEQUENCES = [ [1, 6, 3], [2, 6, 3], [5, 9, 3], [6, 2, 3], [1, 8, 7], [8, 1, 7...
require 'test_helper' class TreesControllerTest < ActionController::TestCase setup do # authenticate activate_authlogic UserSession.create(users(:testuser1)) @tree = trees(:one) @user = users(:testuser1) end test "should get index" do get :index assert_response :success asse...
describe Auth0Service do let(:cog) { CogService.include(Auth0Service) } specify { expect(cog).to be_kind_of(Module) } specify {expect(cog).to respond_to(:token)} specify {expect{cog.options}.to raise_error(NoMethodError)} specify { stub_request(:post, "https://ncimatch.auth0.com/oauth/ro").to_return(...
require File.expand_path(File.dirname(__FILE__) + '/../../../spec_helper') describe "/admin/blogs/new.html.erb" do include Admin::BlogsHelper before(:each) do @blog = mock_model(Blog) @blog.stub!(:new_record?).and_return(true) @blog.stub!(:title).and_return("MyString") @blog.stub!(:short_name).a...
class CreateMealAssignments < ActiveRecord::Migration def change create_table :meal_assignments do |t| t.date :assigned_on, null: false t.references :meal, index: true, foreign_key: true, null: false t.timestamps null: false end end end
require 'io/console' require 'zabby' def get_config token = ENV['ZABBIX_API_TOKEN'] username = ENV['ZABBIX_API_USERNAME'] password = ENV['ZABBIX_API_PASSWORD'] unless username print "Enter username: " password = STDIN.noecho(&:gets).chomp end unless password print "Enter password for #{usernam...
require 'pry' require_relative './cat.rb' require_relative './dog.rb' require_relative './fish.rb' class Owner @@all = [] @@count = [] @@reset_all = [] attr_reader :species attr_accessor :pets, :name, :fish, :cat, :dog, :mood def initialize(pets={fishes: [], cats: [], dogs: []}, species) @species = species ...
require 'file_mover/ftp_base' require 'file_mover/handlers' require 'file_mover/utils' require 'net/sftp' module FileMover class Sftp < FtpBase include Handlers private def session logger.debug{"#{self}: about to sftp login on #{host}, user #{user}"} assert :host, :user, :remote_dir o...
require "mean" describe Mean do let(:single_1) { stub(:single, :dnf? => false, :time => 42) } let(:single_2) { stub(:single, :dnf? => false, :time => 41) } let(:singles) { [single_1, single_2] } context "zero DNFs" do subject { Mean.new(singles) } its(:result) { should == 41.5 } end context "one...
class User < ActiveRecord::Base NAME_REGEX = /\A[a-zA-Z\-\!\@]+\z/ EMAIL_REGEX = /\A[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\z/ has_many :projects validates :first_name, format: { with: NAME_REGEX }, length: (2..100) validates :last_name, format: { with: NAME_REGEX }, length: (1..100) validates :email,...
# encoding: utf-8 module Pakman # downcase and remove .txt (if anywhere in name) # e.g. welcome.quick.txt becomes welcome.quick # welcome.txt.quick becomse welcome.quick # s6blank.txt becomes s6blank def self.pakname_from_file( path ) File.basename( path ).downcase.gsub( '.txt', '' ) end ...
# Load the Rails application. require File.expand_path('../application', __FILE__) require 'haml' # Initialize the Rails application. def time_scale(d1, d2) diff = d1>d2 ? d1-d2 : d2-d1 weeks = diff * 1.65344e-6 days = Rails.application.config.time_scale[:year]*weeks ig_years = days/Rai...
class AddTimesToApartments < ActiveRecord::Migration[5.0] def change add_column :apartments, :time_from_megans, :integer add_index :apartments, :time_from_megans add_column :apartments, :time_from_pipers, :integer add_index :apartments, :time_from_pipers end end
require 'spec_helper' describe 'Employee' do before(:each) do @employee = Employee.new("hiro", "manager", 10000) end it 'Can add observer' do payroll = double('Payroll') allow(payroll).to receive(:update) expect{ @employee.add_observer(payroll) }.not_to raise_error end it 'Can trigger chan...
require "rails_helper" feature "User Management" do given(:admin) { FactoryGirl.create(:admin) } given(:stockholder) { FactoryGirl.create(:user, :stockholder) } given(:manager) { FactoryGirl.create(:user, :manager) } scenario "admin user" do visit admin_users_path(as: admin) expect(current_path).to eq...
class CreateGames < ActiveRecord::Migration def change create_table :games do |t| t.belongs_to :tournament, :null => false t.timestamps end add_index :games, :tournament_id end end
require_dependency 'embed_controller' class ::EmbedController def comments include_first = SiteSetting.embed_complete_enabled count_diff = include_first ? 0 : 1; embed_url = params[:embed_url] embed_username = params[:discourse_username] topic_id = nil if embed_url.present? topic_...
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render(html: "hello, world!!") # render html: number # render html: "hello, world!" end end #render のみで出力してみたがエラー、html形式でというのが必要。render methodの引数がハッシュになっている。 #render メソッドの引数がハッシュだから{}をつけて呼び出したが、エ...
require 'rails_helper' describe SpecializationSkill do it { should belong_to(:specialization) } it { should allow_value(build(:maker)).for(:specialization) } it { should_not allow_value(nil).for(:specialization) } it { should belong_to(:skill) } it { should allow_value(build(:inovation)).for(:skill) } it ...
class ProgramCyclesController < ApplicationController before_action :set_program_cycle, only: [:show, :edit, :update, :destroy] # GET /program_cycles # GET /program_cycles.json def index @program_cycles = ProgramCycle.all end # GET /program_cycles/1 # GET /program_cycles/1.json def show end #...