text stringlengths 10 2.61M |
|---|
class ModifyVolumes < ActiveRecord::Migration
def self.up
add_column :volumes, :capacity, :integer, :limit => 8
add_column :volumes, :size, :integer, :limit => 8
add_column :volumes, :vendor, :string
add_column :volumes, :businfo, :string
add_column :volumes, :serial, :string
add_column :volum... |
namespace :utilities do
require 'open-uri'
desc "Add Founding Users"
task add_founding_users: :environment do
User.create(email: "ali@testing.com", password: "testing", role: "client",
first_name: "Ali", last_name: ""
)
User.create(email: "v@testing.com", password: "testing", role: "administra... |
require 'rails_helper'
describe Linter::Collection do
describe '.for' do
context 'when the given filename maps to a linter' do
it 'instantiates the collection with the matching linters' do
hound_config = double('HoundConfig')
build = double('Build')
pull_request = double(
... |
class DepartmentsController < ApplicationController
def show
d = Department.find(params[:id])
@departname = d.name
@classes = d.classes.sort {|a,b| a.rank_department <=> b.rank_department}
end
end
|
# Worker Class
class QueueWorker
include Shoryuken::Worker
shoryuken_options queue: -> { "#{Rails.configuration.environment.fetch('queue_name')}" }, auto_delete: true
def perform(_sqs_message, message)
begin
message = JSON.parse(message).symbolize_keys!
processor_key = message.keys.first
c... |
class AddPayPeriodToUsers < ActiveRecord::Migration[5.0]
def change
add_column :users, :pay_period, :string
end
end
|
class User < ActiveRecord::Base
attr_accessible :email, :password, :salt , :password_confirmation
before_save :encrypt_password
after_save :clear_password
has_one :profile
has_many :posts
has_many :comments
EMAIL_REGEX = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i
validates :email, :presence => true,... |
require 'rails_helper'
RSpec.describe Book, type: :model do
subject { create(:book) }
it "is valid with valid attributes" do
expect(subject).to be_valid
end
it "is not valid without a category" do
subject.category_id = nil
expect(subject).to_not be_valid
end
it "is not valid without a publi... |
require 'spec_helper'
describe UserFeed do
let!(:asha) { User.create(username: 'asha', email: 'blah@gmail.com') }
let!(:feed) { Feed.create(uid: 'blah', type: 'RSSFeed') }
describe 'create relationship method' do
it 'will create relationship between user and feed' do
ashafeed = UserFeed.create_relat... |
require "test_helper"
class CartTest < MiniTest::Test
def test_serializes_to_hash
cart = Cart.new
cart.add_item 1
assert_equal cart.serialize, session_hash["cart"]
end
def test_builds_from_hash
cart = Cart.build_from_hash session_hash
assert_equal 1, cart.items.first.product_id
end
pr... |
module HQMF2JS
module Generator
class CodesToJson
def self.hash_to_js(hash)
hash.to_json.gsub(/\"/, "'")
end
def self.from_value_sets(value_sets)
# make sure we have a string keyed hash
translation = {}
value_sets.each do |value_set|
... |
class ClassSection < ActiveRecord::Base
has_one :discussion_board
belongs_to :user
after_create :gen_keys
has_many :weights
has_many :documents
has_many :class_packages
has_many :packages, :through => :class_packages
has_many :attendance_records
#composite_primary_key
self.primary_keys = :id
... |
class RenameMd5Column < ActiveRecord::Migration
def up
rename_column(:archives, :md5, :file_digest)
end
def down
rename_column(:archives, :file_digest, :md5)
end
end
|
class ChangeForeignKeysToInteger < ActiveRecord::Migration[5.1]
def change
change_column :provinces, :country_id, :integer
change_column :cities, :province_id, :integer
change_column :residences, :city_id, :integer
rename_column :people, :res_id, :residence_id
change_column :people, :residence_id, :in... |
class Post < ApplicationRecord
MAX_POST_IMAGES_LENGTH = 3
belongs_to :user
has_many :post_images, dependent: :destroy
has_many :post_likes, dependent: :destroy
accepts_nested_attributes_for :post_images, allow_destroy: true
validates :body, presence: true
validates :user_id, presence: true
validates :p... |
require 'spec_helper'
describe Status::Jenkins do
subject {Status::Jenkins.new("")}
before do
Status.stub(:config => stub(:attrs => {}, :parsed => {}))
Status::Request.any_instance.stub(:get)
Status.stub(:system_warn)
end
context "#state" do
it "changes slashes to underscores" do
Statu... |
# represents a user that does not have an account with
# us only reservations
class Guest < ActiveRecord::Base
has_many :reservations, as: :user
end
|
require 'spec_helper'
RSpec.describe Bsale::DocumentType do
before do
Bsale.configure do |config|
config.access_token = ENV['BSALE_KEY']
end
end
context '#all' do
it 'returns a list of instance classes' do
document_type = Bsale::DocumentType.new
expect(document_type.all).to be_a_k... |
module Voted
extend ActiveSupport::Concern
included do
before_action :set_votable, only: %i[up down cancel_vote]
def up
authorize! :up, @votable
@votable.create_positive_vote(current_user)
success_response
end
def down
authorize! :down, @votable
@votable.create_negat... |
require "sidekiq"
module SidekiqBulkJob
module BatchRunner
module ClassMethods
# 当使用sidekiq work的时候可以直接使用下面的方法,会把同类型的job汇总在1分钟内批量执行
# 适合回调时候要执行的job,减少sidekiq job创建的数量,减少线程调度花费的时间
# 缺点:job批量执行之后时间会比较久,但是比全部job分开执行时间要短
# 批量异步执行
def batch_perform_async(*args)
SidekiqBulkJob.... |
require 'logger'
# ログ出力用
APP_LOG_PATH = './logs/application.log'
DEV_LOG_PATH = './logs/development.log'
ERR_LOG_PATH = './logs/error.log'
APP_LOGGER = Logger.new(APP_LOG_PATH)
DEV_LOGGER = Logger.new(DEV_LOG_PATH)
ERR_LOGGER = Logger.new(ERR_LOG_PATH)
module NewsLogger
module_function
# アプリケーションログ出力用関数
# @para... |
module CommentsHelper
def edit?(comment)
logged_in? && current_user == comment.user
end
def delete?(comment, post)
logged_in? && (current_user == comment.user || current_user == post.user) # or comment.post.user
end
end
|
require 'mongoid'
require 'date'
class Contribution
include Mongoid::Document
field :date, type: Date
field :value, type: Integer
belongs_to :subject
class << self
def register(date, value)
target = find_or_create_by(date: date)
target.update_attribute(:value, value)
target
end
... |
require 'rails_helper'
RSpec.describe Author, type: :model do
describe Author do
it "has a valid factory" do
expect(FactoryGirl.create(:author)).to be_valid
end
it "is invalid without a firstname" do
expect(FactoryGirl.build(:author, firstname: nil)).not_to be_valid
end
it "is in... |
class SearchForm::Location < SearchForm::Base
attribute :address, String
validates :address, presence: true, length: {minimum: 4}
def search
return Location.none if invalid?
locations = Location.select("#{Location.table_name}.original_address")
.useful
.wh... |
class Garden < ApplicationRecord
# include PgSearch
# pg_search_scope :search_params, against: [ :city ]
validates :name, uniqueness: true, presence: true
validates :price, presence: true
validates :city, presence: true
validates :capacity, presence: true
has_many :reviews, dependent: :destroy
end
|
class CreateConfigWelcomeIndices < ActiveRecord::Migration[4.2]
def change
create_table :config_welcome_indices do |t|
t.string :name, null: false
t.string :panel_partial, null: false
t.boolean :enable_show, default: false
t.timestamps null: false
end
end
end
|
class View
def display_all(recipes)
recipes.each_with_index do |recipe, index|
if recipe.done?
puts "#{index + 1}. [X] - #{recipe.name} (#{recipe.prep_time}): #{recipe.description}
- #{recipe.difficulty_level}"
else
puts "#{index + 1}. [ ] - #{recipe.name} (#{recipe.prep_time})... |
require 'uri'
require ENV['TM_SUPPORT_PATH'] + '/lib/tm/process.rb'
require ENV['TM_SUPPORT_PATH'] + '/lib/ui'
require 'strscan'
%w[json/version json/pure/parser json/pure/generator json/common json/pure json].each do |filename|
require File.dirname(__FILE__) + "/../../lib/#{filename}.rb"
end
class ReviewBoardContr... |
# -*- encoding : utf-8 -*-
module OpenPayU
# A class responsible for dealing with Order
class Order
# Retrieves information about the order
# - Sends to PayU OrderRetrieveRequest
#
# @param [String] order_id PayU OrderId sent back in OrderCreateResponse
# @return [Documents::Response] Respons... |
# encoding: utf-8
$: << 'RspecTests'
$: << 'RspecTests/Generated/duration'
require 'generated/body_duration'
module DurationModule
describe DurationModule::Duration do
before(:all) do
@base_url = ENV['StubServerURI']
dummyToken = 'dummy12321343423'
@credentials = MsRest::Token... |
module NineOneOne
class Error < RuntimeError; end
class NotConfiguredError < Error; end
class ConfigurationError < Error; end
class IncidentReportingError < Error; end
class NotificationError < Error; end
class HttpError < Error; end
class SSLError < HttpError; end
class TimeoutError < HttpError; end
... |
# street -> Calle
# street_number -> Numero Exterior
# interior_number -> Numero Interior
# neighborhood -> Colonia
# location -> Localidad
# reference -> Referencia
# city -> Municipio
# state -> Estado
# country -> Pais
# zip_code -> Codigo Postal
#
module MCFDI
# Address Class for transmitter and receptor.
clas... |
# frozen_string_literal: true
require "spec_helper"
describe GraphQL::Language::DefinitionSlice do
let(:document) { GraphQL.parse(query_string) }
describe "anonymous query with no dependencies" do
let(:query_string) {%|
{
version
}
|}
it "is already the smallest slice" do
as... |
class Video < ActiveRecord::Base
belongs_to :category
# validates :title, :description, presence: :true
validates_presence_of :title, :description, :cover_image_url
def self.search_by_title(search_term)
return [] if search_term.blank?
word = search_term.downcase
where("title LIKE ?", "%#{word}%").o... |
class RemoveIndexCurrentQuestionId < ActiveRecord::Migration[5.2]
def change
remove_index :test_passages, name: "index_test_passages_on_current_question_id"
end
end
|
class WidgetCell < Cell::Rails
helper :cms
build do |page, widget|
"Widget::#{widget.class}Cell".constantize
end
def show(page, widget)
@page = page
@widget = widget
render
end
private
def really_cache?(*args)
RailsConnector::Workspace.current.published?
end
end |
require 'pry'
class Node
attr_accessor :left, :data, :right
def initialize(data, left=nil, right=nil)
@left = left
@data = data
@right = right
end
end
def build_tree(array, start=0, last=0)
#binding.pry
return nil if start > last
#sorts and removes duplicates
array.sort!.uniq!
start = 0
... |
require 'test_helper'
class SettingsTest < Minitest::Test
def teardown
Settings.reload!
end
def test_defaults_same_as_settings
# Make sure these two files are always the same.
# If a user overlays config/settings.yml with an older version of the settings file
# the prepended defaults will fill i... |
class ProcessorsController < ApplicationController
before_action :authenticate_user!
before_action :is_a_processor
before_action :set_quote
def show
@user = current_user
end
end
|
#
# Cookbook Name:: managed_directory
# Recipe:: t_resource_name_symbol
#
# used by chefspec
# Define the managed_directory
managed_directory "/tmp/foo" do
action :clean
end
log :test do
message "LOG: t_resource_name_symbol test."
end
|
class Post < ApplicationRecord
has_many :comments
belongs_to :user
paginates_per 3
validates :message, presence: true, length: {minimum: 10, too_short: "Are you sure that's all you want to write? This doesn't seem like much of a blog post!"}
end
|
# chapter 6
letters = 'aAbBcCDeE'
puts letters.upcase
puts letters.downcase
puts letters.swapcase
puts ' a'.capitalize
puts letters |
# encoding: utf-8
require File.expand_path("../spec_helper", __FILE__)
bug "WTR-332", :watir do
describe "Uls" do
before :each do
browser.goto(WatirSpec.files + "/non_control_elements.html")
end
describe "#length" do
it "returns the number of uls" do
browser.uls.length.should == 2
... |
class PicturesController < ApplicationController
before_action :set_picture, only: [:show, :edit, :update, :destroy]
# GET /pictures
# GET /pictures.json
def index
@pictures = Picture.all
end
# GET /pictures/1
# GET /pictures/1.json
def show
client = Aws::Rekognition::Client.new
# Uncomme... |
# -*- coding: utf-8 -*-
=begin
Escreva um programa para calcular a redução do tempo de vida
de um fumante. Pergunte a quantidade de cigarros fumados por
dia e quantos anos ele já fumou. Considere que um fumante perde
10 minutos de vida a cada cigarro, calcule quantos dias de vida
um fumante perdeŕa. Exiba o total em... |
class Post < ApplicationRecord
belongs_to :user
has_many :likes
has_many :comments
mount_uploader :image, ImageUploader
default_scope -> { order(created_at: :desc) }
scope :active, -> { where active: true }
before_create :set_active
private
def set_active
self.active = true
end
end
|
require 'rails_helper'
describe SkillCategory do
it { should have_many(:specialization_weights) }
it { should have_many(:skills) }
it { should allow_value('foobar').for(:name) }
it { should_not allow_value('foo').for(:name) }
it { should_not allow_value('').for(:name) }
end
|
# Distilled from optparse.rb
#
# The problem is that in the option_list.each loop, each
# same underlying block, so that all of the option handlers get the last block
# rather than their own Proc
class Parser
def initialize
@blocks = Array.new
end
def on(&block)
@blocks << block
end
def parse!
r... |
class RenameTypetoRole < ActiveRecord::Migration
def change
rename_column :passwords, :type, :role
rename_column :notifications, :type, :role
end
end
|
class Projects::TasksController < ApplicationController
before_action :prepare_project_and_story
before_action :prepare_task, except: [:new, :create]
before_action :check_user_authority
def new
@task = Task.new
end
def create
@task = @story.tasks.build(task_params)
if @task.save
redirec... |
class GroupBase < ApplicationController
before_action :set_groups # カレントユーザの所有する団体を@groupsへ
before_action :set_ability # カレントユーザの権限設定を@abilityへ
def set_groups
# ログインしていなければ何もしない
return if current_user.nil?
# 今年のレコード
this_year = FesYear.where(fes_year: Time.now.year)
# 自分の所有するグループで今年に紐づくもの
... |
class Gossip < ApplicationRecord
has_many :comments
has_many :tags, through: :tagossips
belongs_to :user
#validates :title, presence: true, length: { in: 3..14, message: "Votre titre doit être compris entre 3 et 14 caractères" }
validates :content, presence: true
end
|
# getter methods allow you to grab values of instance variables set in initialize method
# setter method sets/changes value of something
class Cookbook
attr_accessor :title
attr_accessor :recipes
attr_accessor :newrecipe
def initialize(title)
@title = title
@recipes = []
end
... |
require 'rails_helper'
RSpec.feature 'list all expenses' do
def login
login_as(create(:user))
end
scenario 'there are no expenses' do
login
visit root_path
expect(page).to have_text 'There are no expenses.'
end
scenario 'there are expenses' do
create(:expense, description: 'Almoço')
... |
class Comment < ApplicationRecord
belongs_to :user
belongs_to :article
belongs_to :formulation
belongs_to :rx
has_many :likes
# todo: validate against bad words in comments
validates :content, presence: true
include PublicActivity::Model
tracked owner: -> (controller, model) { controller&.current_us... |
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.belongs_to :scene, index: true
t.text :text, null: false
t.boolean :from_character, null: false
t.integer :delay, null: true
t.integer :parent_id, null: true
end
end
end |
module PerformanceMacros
def should_take_on_average_less_than(limit, num_trials = 60, &block)
should "take, on average, less than #{limit}" do
result = nil
num_trials.times do
result = if result.nil?
::Benchmark.measure(&block.bind(self))
else
result + ::Benchmar... |
class Comment < ActiveRecord::Base
belongs_to :user, required: true
belongs_to :chat_box, required: true
end
|
require_relative 'db_connection'
require_relative '01_mass_object'
require 'active_support/inflector'
class MassObject
def self.parse_all(results)
all = []
results.each do |result|
all << self.new(result)
end
all
end
end
class SQLObject < MassObject
def self.columns
query = "SELECT * F... |
class Monster < Omega::SpriteSheet
DEATH_DIRECTION_FOREGROUND = "foreground"
DEATH_DIRECTION_BACKGROUND = "background"
DEATH_SPEED_SCALE = 0.02
DEATH_MAX_SCALE = 1.8
DEATH_ANGLE = 20
MAX_VELOCITY_Y = 8
TIMER_HIT = 0.3;
attr_reader :hp, :is_dead, :hitbox, :is_taking_damage
attr_a... |
class PasswordRecoveryToken < ActiveRecord::Base
belongs_to :user
before_save ->(rec){ rec.token ||= Authentication::Token.new.generate}
def password_errors field = :password
return unless self.user.errors.any?
self.user.errors.messages[field]
end
end
|
module QuickbloxApi
module Helpers
def safe_parse(response)
begin
JSON.parse(response, symbolize_names: true)
rescue JSON::ParserError => e
{}
end
end
end
end
|
class FontChenyuluoyan < Formula
version "1.0-motospaced"
sha256 "d8ecd0598634c92f0b29f90aabef8f7916f17aef19b0350883ca7b46979a5373"
url "https://github.com/Chenyu-otf/chenyuluoyan_thin/releases/download/v#{version}/ChenYuluoyan-Thin-Monospaced.ttf"
desc "Chenyuluoyan"
desc "辰宇落雁體"
desc "Open-source traditio... |
require 'yaml'
module Config
class ZoneLookup
def initialize(zone_hash)
@zone_hash = zone_hash
end
def zone_for(component)
@zone_hash.find { |zone, components| components.include?(component) }[0]
end
end
end |
class Message < ApplicationRecord
belongs_to :conversation
belongs_to :user
#belongs_to :sender, foreign_key: 'sender_id', class_name: "User";
#belongs_to :recipient, foreign_key: 'recipient_id', class_name: "User"
# has_many :message_responses, foreign_key: 'message_responded_id',
# ... |
module TranslationCenter
class ApplicationController < ActionController::Base
before_filter :translation_langs_filters
before_filter :authenticate_user!
if Rails.env.development?
# if an exception happens show the error page
rescue_from Exception do |exception|
@exception = exception... |
class StagesController < ApplicationController
before_action :find_stage, only: [:edit, :update, :destroy]
def index
@stages = Stage.all
end
def new
@stage = Stage.new
end
def create
@stage = Stage.new(stage_params)
if @stage.save
redirect_to @stage, notice: 'success'
else
... |
require 'rails_helper'
RSpec.describe PhotosController, type: :controller do
login_user
describe "PATCH #update" do
let(:user) { current_user }
let(:album) { create(:album, user: user) }
let(:created_photo_tags_count) { 3 }
let(:photo) { cre... |
require "rails_helper"
describe "Movies requests", type: :request do
describe "index view" do
it "displays right title" do
visit "/movies"
expect(page).to have_selector("h1", text: "Movies")
end
end
describe "JSON API", type: :request do
let(:genre) { create(:genre, :with_movies) }
l... |
# SOAP4R - marshal/unmarshal interface.
# Copyright (C) 2000, 2001, 2003 NAKAMURA, Hiroshi <nahi@ruby-lang.org>.
# This program is copyrighted free software by NAKAMURA, Hiroshi. You can
# redistribute it and/or modify it under the same terms of Ruby's license;
# either the dual license version in 2003, or any later... |
desc 'one-time address adding for synapse'
task :address_adding_for_synapse => :environment do
organization_id = Organization.find_by_name("Synapse").id
providers = Provider.where("organization_id = ?",organization_id)
providers.each do |p|
options = Address.parse_string_into_options(p.location_string)
A... |
module Admin::AdminHelper
def breadcrumbs(*parts)
separator = "›"
crumbs = parts.map do |part|
crumb_for(part)
end.join(' ' + separator + ' ')
"#{separator} #{crumbs}"
end
def tab_active?(controller_action, kind)
active = controller_action =~ /#{kind}/i ? 'tabOn' : ''
active... |
class Article < ActiveRecord::Base
has_and_belongs_to_many :authors, class_name: 'User'
has_many :posts, as: :record
validates :title, presence: true
validates :lead, presence: true
validates :body, presence: true
validates :published_at, presence: true
validates :photo, presence: true
scope :publishe... |
FactoryGirl.define do
factory :project do
name "New Test Project"
end
end |
# frozen_string_literal: true
module Events
class ShowController < ApplicationController
def show
if event
render json: Oj.dump(serialized_event, mode: :rails)
else
head :unprocessable_entity
end
end
private
def serialized_event
::Serializers::EventTickets.ne... |
class Tag < ActiveRecord::Base
has_and_belongs_to_many :statuses
attr_accessible :tag
validates :tag, :presence => true
end
|
class RequestsController < ApplicationController
# Create
post '/requests' do
if logged_in_recruiter?
request = Request.new(description: params[:description])
vac = current_user.vacancies.find_by(id: params[:vacancy_id])
request.recruiter = current_user
request.vacancy = vac; request.v... |
class PagesController < ApplicationController
before_action :require_admin, only: [:create, :new, :destroy, :edit, :update]
def index
@title = '所有文章'
@pages = Page.all.reverse
end
def show
@page = Page.find(params[:id])
end
def create
@page = Page.new(page_params)
if @page.save
... |
# describes freight or passenger trains
class Train
attr_reader :speed, :carriage_count, :route, :current_station, :number, :type
def initialize(number, type = 'грузовой', carriage_count = 10)
@number = number
@type = type
@carriage_count = carriage_count
@speed = 0
end
def speed_up(speed)
... |
require_relative '../spec_helper'
describe 'Socket#ipv6only!' do
before do
@socket = Socket.new(:INET6, :DGRAM)
end
after do
@socket.close
end
it 'enables IPv6 only mode' do
@socket.ipv6only!
@socket.getsockopt(:IPV6, :V6ONLY).bool.should == true
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'ideas#index'
resources :ideas do
resources :reviews, shallow: true
end
resources :users, only: [:new, :create]
resources :sessions, only: [:new, :create] do
de... |
class Category < ActiveRecord::Base
has_many :outflows
validates_presence_of :name
validate :name, presence: true
validates_uniqueness_of :name
validate :name, uniqueness: true
end
|
FactoryBot.define do
factory :guest do
name ''
email ''
phone_number ''
plus_one ''
uuid ''
confirmed false
verification_code nil
trait :with_name do
name 'Joe Bloggs'
end
trait :with_email do
email 'joe.bloggs@example.com'
end
trait :with_invalid_email ... |
class CreateBooksBookstoresTable < ActiveRecord::Migration
def up
create_table :books_bookstores, :id => false do |t|
t.integer :book_id
t.integer :bookstore_id
t.timestamps
end
end
def down
drop_table :books_bookstores
end
end
|
require 'formula'
class Lftp <Formula
@url='http://ftp.yars.free.net/pub/source/lftp/lftp-3.7.15.tar.gz'
@homepage='http://lftp.yar.ru/'
@md5='6c43ffdb59234ff0533cfdda0c3c305c'
depends_on 'readline'
def install
ENV['CXXFLAGS'] += " -fno-exceptions -fno-rtti -fno-implement-inlines"
ENV['LDFLAGS'] +=... |
########################################################
# Defines the main methods that are necessary to execute a plugin
########################################################
class Plugin
#Loads the plugin's execution
def initialize(params,stbb_db,bbtools)
@params = params
@stbb_db = stbb_db
@bbtoo... |
require_relative '../request_spec_helper'
feature 'Users' do
let(:user) { create(:user) }
scenario 'can sign-up for an account' do
visit new_user_registration_path
page.should have_content('Sign Up')
fill_in 'First name', :with => 'Charles'
fill_in 'Last name', :with => 'Gerald'
fill_... |
class CreateMemberships < ActiveRecord::Migration
def change
create_table :memberships do |t|
t.references :user, index: true, null: false
t.references :belongable, polymorphic: true, index: true, null: false
t.references :creator, index: true, null: false
t.text :notes
t.integer :sc... |
class CreateCards < ActiveRecord::Migration
def change
create_table :cards do |t|
t.integer :set, null: false
t.string :hearthstone_id, null: false
t.integer :card_type, null: false
t.string :name, null: false
t.string :name_ja
t.text :text
... |
require 'rails_helper'
RSpec.describe "Static pages", :type => :request do
describe "Home page" do
it "home page has welcome message" do
visit root_path
expect(page).to have_content('Mail Tailor')
end
end
end
|
require_relative './choice'
class Paper < Choice
def initialize
@name = 'Paper'
end
def can_win?(another_choice)
another_choice.name == 'Rock'
end
end |
# lib/rook.rb
class Rook
def initialize(pos_x, pos_y, color)
@pos_x = pos_x
@pos_y = pos_y
@color = color
end
def move?(dst_x, dst_y)
dx = (dst_x - @pos_x).abs
dy = (dst_y - @pos_y).abs
dx == 0 || dy == 0
end
end |
class ChangeSuppilerToSupplierInOrder < ActiveRecord::Migration
def change
rename_column :orders, :suppiler_id, :supplier_id
end
end
|
# Please copy/paste all three classes into this file to submit your solution!
class Restaurant
@@all = []
attr_accessor :name
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def self.find_by_name(restaurant_name)
self.all.find { |rest| rest.name = restauran... |
module Ripley
module Formatters
module Object
class FileName
# generate an object string identifier for the call stack that is showed to the user
def format(binding, caller_index=nil)
binding.short_file.split('/').last.gsub(/\..+/, '')
end
end
end
end
end
|
class Api::V1::SearchesController < ApplicationController
def show
if params[:query]
render json: YoutubeApi.search(params[:query])
else
render json: []
end
end
end
|
class Mentor #mentoring experience
include Mongoid::Document
#fields to include what to mentor
field :notes, type: String
# field :courses_description, type: String
# has_many :agreements
belongs_to :user
# belongs_to :skill
has_and_belongs_to_many :skills
end |
# new session
get '/login' do
erb :'/sessions/new'
end
#create session
post '/login' do
user = User.find_by(username: params[:username])
if user && user.password == params[:password_hash]
session[:user_id] = user.id
redirect '/'
else
# @error = "Something went wrong. Please try again."
@errors ... |
class User < ActiveRecord::Base
has_many :orders
has_many :searches
has_many :payments, through: :orders
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.