text stringlengths 10 2.61M |
|---|
require "rvm/capistrano"
require "bundler/capistrano"
set :application, "valentinos"
set :domain, "77.73.5.134"
set :user, "adam"
set :scm, :git
set :repository, "git@github.com:adamedia/valentinos.git"
set :use_sudo, false
set :branch, "master"
set :deploy_via, :remote_cache
set :deploy_to, "/home/#{user}/valentin... |
require 'pry'
class GetInfo
def exchange(response, options)
to_convert_number = response['rates'][options[:to]] if response['base'] == options[:from] && response['rates']
unless to_convert_number.nil?
money = options[:amount].to_f * to_convert_number
puts "#{money} #{options[:to]}"
else
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# This Vagranfile produces a VM with heroku-toolbelt ready to go.
# It opens up port 5000 from inside the guest VM machine, and binds
# it to port 8080 of the host os.
# To use heroku, do a 'vagrant ssh' and start hacking.
Vagrant.configure(2) do |config|
config.vm.... |
class CreateCouchTimes < ActiveRecord::Migration
def self.up
create_table :couch_times do |t|
t.integer :duration
t.string :comment
t.timestamps
end
end
def self.down
drop_table :couch_times
end
end
|
shared_examples "sanitized presenter" do |factory_name, field_to_sanitize, presented_field = field_to_sanitize|
it "sanitizes #{field_to_sanitize}" do
bad_value = "<script>alert('got your cookie')</script>"
presented = FactoryGirl.build factory_name, field_to_sanitize => bad_value
json = described_class.... |
class AddUserIdToTeas < ActiveRecord::Migration
def change
add_column :teas, :user_id, :integer
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }
# before_action :authorized
def authorized
render json: { error: 'JWT is invalid' }, status: :unauthorized unless logged_in?
end
def encode_token(payload)
token_life = 2.hours
cache_key ... |
require 'rails_helper'
RSpec.feature "user_visits_the_root_path" do
context "and needs to register as a new user" do
scenario "they see login fields and a button to register" do
visit root_path
expect(page).to have_content("GifGenerator")
expect(page).to have_link("Login Page", login_path)
... |
$: << File.dirname(__FILE__)
require 'socket'
require 'http.rb'
port = 8080
server = TCPServer.open(port)
process_number = 1
class String
def self.random(size=20)
set = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten
(1..size).map{ set[rand(set.length)] }.join
end
end
def generate_cookie
require 'dige... |
class Person
include DataMapper::Resource
property :id, Serial
property :type, Text, :required => true
property :name, Text, :required => true
property :email, Text, :required => true
property :twitter, Text
property :github, Text
end
|
require_relative 'test_helper'
require 'robot_factory/laser_bank'
describe LaserBank do
before do
layout = "#|#|#|##"
@laser_bank = LaserBank.new layout: layout, fires_on: {even: true}
end
describe "#load_layout" do
it "should load layout" do
[0, 2, 4, 6, 7].each do |i|
refute @lase... |
# frozen_string_literal: true
# rubocop:todo all
require 'spec_helper'
describe 'Auto encryption client' do
require_libmongocrypt
require_enterprise
min_server_fcv '4.2'
context 'after client is disconnected' do
include_context 'define shared FLE helpers'
include_context 'with local kms_providers'
... |
module Orchestrate
# @return [String] The version number of the Orchestrate Gem
VERSION = "0.9.0"
end
|
class SurveyAnswer
QuestionsPerStage = 10
attr_reader :survey_id, :answer_id
alias :id :answer_id
def initialize(db, survey_id, answer_id)
@db = db
@survey_id = survey_id
@answer_id = answer_id || create_answer(survey_id)
end
def state
@db.get "answer:#{@answer_id}:state"
end
def que... |
require 'rails_helper'
RSpec.describe Users::InvitationsController, type: :request do
let(:user) { FactoryBot.create(:user, :with_motherboard) }
let(:motherboard) { user.motherboards.first }
before(:each) do
sign_in user
end
describe '#edit' do
context 'new user' do
it 'should render the f... |
require 'rubug/callback'
require 'test/unit'
class TestCallback < Test::Unit::TestCase
def test_method_argument_not_callable
non_callable_object = Object.new
assert_raise(ArgumentError) {
Rubug::Callback.new(non_callable_object)
}
end
def test_method_arity_1
arity_1_method = lambda{ |x| n... |
class VersionCommitter < ActiveRecord::Base
belongs_to :author, -> { where "version_committers.role in ('author', 'all')" }
belongs_to :version
belongs_to :maintainer, -> { where "version_committers.role in ('maintainer', 'all')" },
class_name: "Author", foreign_key: :author_id
@@valid_roles = [:author, :m... |
class Promotion < ActiveRecord::Base
attr_accessible :discount, :end_date, :product_id, :promotion_description, :promotion_name, :start_date
belongs_to :product
def name
promotion_name
end
end
|
require 'spec_helper'
describe ComicScraper do
describe 'initialization' do
it 'formats date into string with proper format' do
wednesday = Date.new(2015, 01, 07)
this_wednesday = wednesday.strftime('%m/%d/%y')
expect(this_wednesday).to eq '01/07/15'
end
end
end
|
require 'spec_helper'
describe LogStasher do
it 'has a version' do
expect(::LogStasher::VERSION).not_to be_nil
end
it 'has a logger' do
expect(::LogStasher.logger).to be_a_kind_of(::Logger)
end
it 'stores a callback for appending fields' do
callback = proc { |fields| fail 'Did not expect this t... |
# Read about factories at http://github.com/thoughtbot/factory_girl
Factory.define :user_profile do |f|
f.user { |p| p.association(:user) }
f.language "en"
end
|
class ArticleContent < ActiveRecord::Base
before_save :generate_short_content
belongs_to :article
def generate_short_content
helper = ActionController::Base.helpers
content = helper.truncate(helper.strip_tags(self.content).gsub(/\s/i,''),:length=>255).strip
self.article.content = content
sel... |
class CreateNodeRacks < ActiveRecord::Migration
def self.up
create_table :node_racks do |t|
t.integer :data_center_id
t.text :label
t.timestamps
end
end
def self.down
drop_table :node_racks
end
end
|
class AddGhostToInstruments < ActiveRecord::Migration
def change
# ghost = true signifies that this instrument is a template instrument for the ucl
# ghost instruments have no evaluations and thus no workers and no evaluators
add_column :instruments, :ghost, :boolean, default: false
end
end
|
json.success @success
if @success
json.set! :result do
json.array!(@downlines) do |downline|
json.extract! downline, :id, :first_name, :last_name, :email, :xango_id, :iuvare_id, :sponsor_xango_id, :placement_xango_id, :active, :payment_expiration, :xango_rank, :picture, :downline_position, :upline_id, :picture
... |
class Restaurant < ActiveRecord::Base
self.per_page = 10
has_many :menu_items
# TODO: Lookup and validate address
validates :name, :address_line_1, :city, :state, :zip, presence: true
validates_numericality_of :rating, greater_than_or_equal_to: 0, less_than_or_equal_to: 5, allow_nil: true
end |
class User < ApplicationRecord
validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i, message: 'Email sai' }
before_save :set_role
has_many :parking_slot_reservations
has_many :vehicles, dependent: :destroy
devise :database_authenticatable, :registerable,
:recoverable, :rememberabl... |
require 'rails_helper'
describe Formulation do
let(:formulation) { FactoryBot.create(:formulation) }
describe 'validations' do
it 'is valid and saveable' do
new_formulation = FactoryBot.build(:formulation)
expect(new_formulation).to be_valid
expect(new_formulation.save).to be_truthy
... |
class CreateAlternateNames < ActiveRecord::Migration
def self.up
create_table :alternate_names do |table|
table.integer :simple_object_id
table.string :name
end
end
def self.down
drop_table :alternate_names
end
end
|
Gem::Specification.new do |s|
s.name = 'Wheniwork-api'
s.version = '0.0.1'
s.date = '2014-03-24'
s.summary = 'When I Work API v2 Wrapper'
s.description = ''
s.authors = ["Adam Meech"]
s.email = 'adam.meech@thisclicks.com'
s.files = ["lib/wheniwork-api.rb"]
s.homep... |
module D12P1
class D12P1
def run(input)
input.map! do |row|
[row[0], row.chomp[1..-1].to_i]
end
position = Matrix[[0],[0]]
direction = Matrix[[1],[0]]
input.each do |command|
case command[0]
when "N"
position += Matrix[[0],[-1]]*command[1]
wh... |
class GamesController < ApplicationController
def edit
@game = Game.find(params[:id])
end
def update
@game = Game.find(params[:id])
@game.update_attributes(game_params)
redirect_to root_path
end
def game_params
params.require(:game).permit(:hometeam_prediction, :awayteam_prediction)
... |
class Article < ActiveRecord::Base
@@per_page = 10
cattr_reader :per_page
attr_accessible :description, :image_url, :title, :url, :comment
attr_accessor :images
validates_presence_of :url, :title
def images_for_select
@images ||= [image_url]
@images.each_with_index.collect{ |url, index| ["Thumbnai... |
# encoding: utf-8
require 'test/unit'
require "./lib/import/scraper04.rb"
class TestScraper04 < Test::Unit::TestCase
def scraper
s = Scraper04.new "expreports"
end
def test_items
s = Scraper04.new "expreports"
assert_equal 14, s.items.length
assert_equal "XR1-1", s.items.first
s = Scraper... |
require 'pry'
class Parser
def initialize(asmFile)
end
def hasMoreCommands
#If there are no more commands
#false
#Else
#true
end
def advance
#The next command becomes the current command
end
def commandType
#If first character of the current command is '@'
... |
class User < ActiveRecord::Base
has_many :game_libraries
has_many :games, through: :game_libraries
end |
require './store'
class Discount
@@register_detail = Store.register_detail
def initialize
add_discount
Store.show_item_list
end
def add_discount
discount(:store_employees)
discount(:senior_citizens)
puts "Do you want to add Discount for items (Y/N)?"
discount = gets.chomp
if discount == "Y"
puts ... |
class SyncActivityJob < ApplicationJob
include Sidekiq::Worker
sidekiq_options retry: false
queue_as :default
def perform(activity_id, athlete_id)
::Sync::Activity.new(activity_id, athlete_id).call
end
end
|
# See the wiki for details:
# https://github.com/ryanb/cancan/wiki/Defining-Abilities
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
alias_action :create, :read, :update, :destroy, :to => :crud
can :crud, User, id: user.id
can :crud, User if user.admin?
can :res... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def test_authentication
@user = users(:admin)
refute_nil @user.authenticate(:username)
refute_nil @user.authenticate(:password)
end
def test_username_must_be_present
@user = User.new(username: " ", password: "pword")
refute @u... |
class Blog < ActiveRecord::Base
validates :title, presence: true
validates :description, presence: true
delegate :id, :title, to: :category, prefix: true, allow_nil: true
belongs_to :admin
belongs_to :category
end
|
require 'test_helper'
class UserTwosControllerTest < ActionDispatch::IntegrationTest
setup do
@user_two = user_twos(:one)
end
test "should get index" do
get user_twos_url
assert_response :success
end
test "should get new" do
get new_user_two_url
assert_response :success
end
test "s... |
module Abroaders
module Cell
# A `<span>` with some text and with data attributes that can be activated
# by JS to make a Bootstrap tooltip.
class SpanWithTooltip < Abroaders::Cell::Base
# Don't use a 'model'; let the caller pass in an options hash as the
# *first* argument.
#
# @o... |
# encoding: utf-8
require "spec_helper"
module MobileStores
describe "WindowsStore" do
describe ".find" do
it "should select single app by ID" do
app = WindowsStore.new.find("angry-birds/9168c4f3-217b-4a29-b543-7513bb4ae2ed")
app.should_not be_nil
[:title, :application_id, :creato... |
class DropHeartImagings < ActiveRecord::Migration[5.0]
def change
drop_table :heart_imagings
end
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module Foundat... |
class RenameCatsTableToGarments < ActiveRecord::Migration
def change
rename_table :cats, :garments
rename_table :order_cats, :order_garments
rename_table :cat_breeds, :garment_breeds
end
end
|
RSpec.describe "Users", type: :request do
describe "GET /users" do
let!(:users) { create_list(:user, 3) }
it "returns users" do
get users_path
expect(response.parsed_body.count).to eq(3)
end
end
end
|
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
class AddStatusToTeamUsers < ActiveRecord::Migration
def change
add_column :team_users, :status, :string, default: "member", index: true
# Fix existing records
TeamUser.all.each do |tu|
tu.status = "member"
tu.save
end
end
end
|
require 'test_helper'
class SubjectsControllerTest < AuthenticatingControllerTestCase
setup do
@subject = subjects(:algebraI)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:subjects)
end
test "should show subject" do
get :show, :id => @sub... |
class Vehicle < ActiveRecord::Base
belongs_to :driver
has_many :passengers, order: 'position asc'
has_many :candidates, dependent: :destroy
validates_presence_of :driver_id, :latitude, :longitude, :token
validates_numericality_of :latitude, :longitude
attr_accessible :latitude, :longitude, :driver_id, ... |
require 'rspec'
require './text_to_numbers.rb'
describe TextToNumbers do
it { expect("five".to_number).to eq 5 }
it { expect("twenty five".to_number).to eq 25 }
it { expect("one thousand six hundred fifty five".to_number).to eq 1655 }
it { expect("two thousand forty".to_number).to eq 2040 }
it { expect("two... |
class AddSlugToUsers < ActiveRecord::Migration
def change
add_column :users, :slug, :string
add_index :users, :slug, :unique => true
User.reset_column_information
User.all.each do |user|
user.slug = user.name.parameterize
user.save!
end
change_column :users, :slug, :... |
class BudgetPresenter < SimpleDelegator
def budget_type
return if super.blank?
I18n.t("form.label.budget.budget_type.#{super}")
end
def iati_status
return if super.blank?
Codelist.new(type: "budget_status", source: "iati").hash_of_named_codes.fetch(super)
end
def period_start_date
return... |
require 'wsdl_mapper/svc_desc_parsing/parser_base'
require 'wsdl_mapper/svc_desc/wsdl11/binding'
module WsdlMapper
module SvcDescParsing
class BindingParser < ParserBase
def parse(node)
name = parse_name_in_attribute 'name', node
binding = Binding.new name
binding.type_name = parse... |
ActiveAdmin.register Order do
permit_params :name
end
|
require "discordrb"
require "yaml"
require "net/http"
require "uri"
require "json"
class HibikiBot
attr_accessor :bot
yaml = YAML.load_file("secret.yml")
TOKEN = yaml["token"].freeze
CLIENT_ID = yaml["client_id"].freeze
HOT_PEPPER_API_HOST = "http://webservice.recruit.co.jp/hotpepper/gourmet/v... |
class Article < ActiveRecord::Base
belongs_to :category
attr_accessible :body, :category, :name
validates :body, :name, :presence => :true
end
|
require 'thor'
require 'pompeu'
module Pompeu
include Logging
class CLI < Thor
desc "import [language]", "adds changes from files to the database"
def import language
Logging.logger.info "text files -> DB"
pompeu = Pompeu.new
pompeu.import language
pompeu.save
end
desc "... |
def reads_a_file(file)
File.read(file)
end
def character_count_with_spaces(file_string)
file_string.length
end
def character_count_without_spaces(file_string)
file_string.split(" ").join.length
end
def line_count(file_string)
file_string.lines.count
end
def word_count(file_string)
file_string.split("... |
class PvArrayTestsController < ApplicationController
before_action :authenticate_user!
before_action :require_viewer, only: [ :show ]
before_action :require_editor, except: [ :show ]
def index
end
def show
@pv_array_test = PvArrayTest.find(params[:id])
@string_tests = @pv_array_test.string_tests
... |
class Backoffice::AnotherServicesController < Backoffice::BackofficeController
def index
@another_services = Anotherservice.order(:id)
end
def new
@another_service = Anotherservice.new
end
def create
another_service = Anotherservice.new(another_service_params)
if another_service.save
... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :omniauthable
attr_accessor ... |
class AddAssetTypeToAssets < ActiveRecord::Migration[4.2]
def change
add_column :assets, :asset_type, :integer
end
end
|
module Sparrow
module Transitions
LINEAR = "linear"
RANDOMIZE = "randomize"
EASE_IN = "easeIn"
EASE_OUT = "easeOut"
EASE_IN_OUT = "easeInOut"
EASE_OUT_IN = "easeOutIn"
EASE_IN_BACK = "easeInBack"
EASE_... |
require 'trellohub/form/card'
require 'trellohub/form/issue'
module Trellohub
class Form
include Form::Card
include Form::Issue
class << self
def common_attributes
%i(
key
state
imported_from
)
end
def origin_attributes
%i(
... |
ActiveAdmin.register Promotion do
index do
column :promotion_name
column :promotion_description
column :discount do |model|
number_to_percentage model.discount, :precision => 0
end
column :start_date
column :end_date
default_actions
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_user
# ask me (Peter) if any of this ruby jargon is confusing
# this is the verbose version of the line 17
# if session[:user_id] and User.exists?(session[:user_id])
# if !@current_user
# @cu... |
class AddWorkoutGroupIdToWorkouts < ActiveRecord::Migration[6.1]
def change
add_reference :workouts, :workout_group, null: false, foreign_key: true
end
end
|
require_relative '../test_helper'
class VersionTest < ActiveSupport::TestCase
test "should have item" do
v = create_version
assert_kind_of ProjectMedia, v.item
end
test "should have annotation" do
with_versioning do
u = create_user
t = create_team
create_team_user user: u, team: t
... |
require 'test_helper'
class AnforasControllerTest < ActionDispatch::IntegrationTest
setup do
@anfora = anforas(:one)
end
test "should get index" do
get anforas_url
assert_response :success
end
test "should get new" do
get new_anfora_url
assert_response :success
end
test "should cre... |
class ApplicationController < ActionController::API
respond_to :json, :html
include ActionView::Helpers::DateHelper
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
# protect_from_forgery with: :exception
# protect_from_forgery with: :null_session
# b... |
class AddAvatarColumnsToEmployees < ActiveRecord::Migration
def change
add_column :employees, :avatar_file_name, :string
add_column :employees, :avatar_content_type, :string
add_column :employees, :avatar_file_size, :integer
add_column :employees, :avatar_updated_at, :datetime
end
end
|
class AddReferenceToRelay < ActiveRecord::Migration[5.2]
def change
add_reference :relays, :shops
end
end
|
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
private
def authenticate_any!
return true if admin_signed_in? || user_signed_in?
false
end
end
|
# Customise this file, documentation can be found here: https://docs.fastlane.tools
# All available actions: https://docs.fastlane.tools/actions/
# can also be listed using the `fastlane actions` command
# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`
# If yo... |
require 'spec_helper'
describe Product do
describe "#score" do
subject { product.score }
let(:product) { Product.new }
def create_point(type: :good, product: nil)
create("#{type.to_s}_point".to_sym,
point: create(:point, article: create(:article, product: product))
)
end
it ... |
#!/usr/bin/env ruby
class RGBColour
def initialize(red, green, blue)
unless red.between?(0,255) and green.between?(0,255) and blue.between?(0,255)
raise ArgumentError, "invalid RGB parameters: #{[red, green, blue].inspect}"
end
@red, @green, @blue = red, green, blue
end
attr_reader :red, :green... |
module WithWinnerRules
def has_won?(a_player)
winner_rules.any?{ | rule | rule.has_won?(a_player, self) }
end
private
def row_winner_rules
Board.positions_range.map{ | row | RowWinnerRule.new(row) }
end
def column_winner_rules
Board.positions_range.map{ | column | ColumnWinnerRule.n... |
require 'HttParty'
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of t... |
class SectionsController < ApplicationController
before_action :authenticate_user!
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :set_section, only: [:destroy, :edit, :update]
def new
@section = current_user.sections.build
end
def create
@user = current_user
@sect... |
class FabcompaniesController < ApplicationController
before_action :set_fabcompany, only: [:show, :edit, :update, :destroy]
# GET /fabcompanies
# GET /fabcompanies.json
def index
@fabcompanies = Fabcompany.all
end
# GET /fabcompanies/1
# GET /fabcompanies/1.json
def show
end
# GET /fabcompani... |
class Gift < ActiveRecord::Base
belongs_to :order
has_many :article_gifts, dependent: :destroy
has_many :articles, through: :article_gifts
has_many :accompaniment_gifts, dependent: :destroy
has_many :accompaniments, through: :accompaniment_gifts
end
|
class ApplicationController < ActionController::Base
before_filter :set_lang
protect_from_forgery
def set_lang
if request.subdomains.first=='en'
I18n.locale = 'en'
else
I18n.locale = 'fr'
end
end
def after_sign_in_path_for(resource)
dashboard_path
end
def rescue_404
redi... |
class Admin::TicketsController < ApplicationController
skip_before_filter :verify_authenticity_token, :only => [:destroy]
access_control do
allow :admin, :all
end
#layout "inadmin"
layout "admin_20141208"
before_filter :load_combos
def index
@tickets = Ticket.all_active
end
def show
... |
class Ticket
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :numbers, :size, :attempts
AttemptsDropdown = [["1 time", 1],
["104 times (twice a week for a year)", 104],
["1,040 times (twice a week for 10 years)", 1040]]
SizeDropdown = ... |
module ApplicationHelper
def current_user
@current_user
end
def current_user?
current_user.present?
end
end
|
require 'digest/sha1'
require 'bcrypt'
class User
include MongoMapper::Document
include BCrypt
before_create :create_feed_key
key :email, String
key :passwordHash, String
key :resetPasswordCode, String
key :resetPasswordCodeExpires, Time
key :thirdPartyAu... |
class AddAuditReportIdToAttachments < ActiveRecord::Migration
def change
add_column :attachments, :audit_report_id, :integer
end
end
|
class Weight < ActiveRecord::Base
belongs_to :user
validates :weight, :presence => true
validates :waist, :presence => true
validates :neck, :presence => true
validates :weight, :numericality => {:greater_than_or_equal_to => 0.01}
end
|
#!/usr/bin/env ruby
class Isbn
def initialize(input)
@match = /^
(?<group> \d{1,5} )
(?<separator> [-\ ,] )
(?<publisher> \d{1,7} )
\k<separator> # same separator
(?<edition> \d{1,6} )
... |
class ClassDiagram::DiagramasController < ApplicationController
before_action :set_diagrama, only: [:show, :edit, :update, :destroy]
def index
@diagramas = CLDIAG.where(user_id: current_user.id).order(id: :desc)
@title = 'Lista de Diagramas de Classes'
end
def show
flash[:notice] = "Diagrama gerad... |
require 'hand'
describe Hand do
let(:card) {double("Card",:value => :Ace)}
let(:deck) {double("Deck",:draw_card => card)}
subject(:hand) {Hand.new(deck)}
before(:each) {allow(card).to receive(:suit).and_return(:Spades,:Clubs,:Diamonds,:Hearts)}
describe "#initialize" do
it "creates @cards... |
class Employee < ActiveRecord::Base
has_many :daily_reports
validates :name, presence: true
def reports_for_range(range)
daily_reports.where('date >= ? and date <= ?', range.begin, range.end )
end
def report_for_date(some_date)
daily_reports.where('date = ?', some_date).first
end
def recieved... |
class RenameWhen < ActiveRecord::Migration
def self.up
rename_column :expenses, :when, :spent_at
end
def self.down
rename_column :expenses, :spent_at, :when
end
end
|
class AddRecoveryHashToTypusUsers < ActiveRecord::Migration
def self.up
add_column :typus_users, :recovery_hash, :string
end
def self.down
remove_column :typus_users, :recovery_hash
end
end
|
module TwilioSMSDeliveryHelper
def set_twilio_signature_header(url, params)
request.headers["X-Twilio-Signature"] =
Twilio::Security::RequestValidator.new(ENV.fetch("TWILIO_AUTH_TOKEN")).build_signature_for(url, params)
end
end
|
# When done, submit this entire file to the autograder.
# Part 1
def sum arr
arr.reduce(0, :+)
end
def max_2_sum arr
if arr.length == 0
return 0
elsif arr.length == 1
return arr[0]
else
arr.sort!
return arr[-1] + arr[-2]
end
end
def sum_to_n? arr, n
if arr.length == 0 || arr.length == 1
... |
class SiteSection < ActiveRecord::Base
belongs_to :site
belongs_to :section
#init position
before_create :assign_position
def assign_position
last_section = SiteSection.where(site_id: self.site_id).order("position ASC").last
if last_section.nil?
self.position = 1
else
self.position = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.