text stringlengths 10 2.61M |
|---|
require_relative '../lib/calc.rb'
describe Calc do
context 'without arguments' do
subject(:calc) {Calc.new}
its(:plus) {should == 0}
its(:minus) {should == 0}
its "after #clear" do
calc.clear
calc.arr.should == []
end
end
context 'with normal args(5,7,-13)' do
subject(:calc) {Calc.new(5, 7, -13)}... |
# == Schema Information
#
# Table name: survey_questions
#
# id :integer not null, primary key
# format :integer default("select_one")
# position :integer
# score_split_question :integer
# text :text
# created_at :datetime ... |
module Fastlane
module Actions
module SharedValues
FLUSH_LOCAL_TAGS_CUSTOM_VALUE = :FLUSH_LOCAL_TAGS_CUSTOM_VALUE
end
# To share this integration with the other fastlane users:
# - Fork https://github.com/fastlane/fastlane/tree/master/fastlane
# - Clone the forked repository
# - Move th... |
class Api::V1::UsersController < ApplicationController
before_action :authorized, except: [:create, :refresh_token]
def create
user = User.new(safe_params)
if user.save
token = encode_token({user_id: user.id})
render json: { username: user.username, token: token }
else
r... |
When /^I fill in fields:$/ do |table|
complete_form_from_table(table)
end
Then /^The field '([^']*)' should be filled in with '([^']*)'$/ do |field, value|
find_field(field).value.should == value
end
When /^I press '([^']*)'$/ do |button_name|
click_button(button_name)
end
Then /^I should see '(.*)'$/ do |tex... |
require 'rails_helper'
RSpec.describe RangeCycle, :ledgers, :range do
it 'initializes with dates' do
repeat = described_class.for name: 'advance', dates: [Date.new(2014, 6, 5)]
expect(repeat.periods.length).to eq 1
expect(repeat.periods.first.first.month).to eq 6
end
describe '#duration' do
des... |
module Alumina
module HIN
# Class that parses HIN files to produce {Molecule} instances. This class is
# not thread-safe! You must instantiate a new parser for each thread of your
# program.
class Parser
# Mapping of HIN file bond types to their symbol values for the {Atom}
# class.
... |
require File.dirname(__FILE__) + '/../spec_helper'
describe ChartsBurndown2Controller do
include Redmine::I18n
before do
Time.set_current_date = Time.mktime(2010,4,16)
@controller = ChartsBurndown2Controller.new
@request = ActionController::TestRequest.new
@request.session[:user_id] ... |
class Game
# Logic related to game variables.
class Variables
# Creates a new Variables object.
def initialize
@values = []
end
# Fetches the value of the game variable with the specified ID.
# @param id [Integer] the ID of the variable to fetch.
# @return [Object] the value of the va... |
class ChangeTableBannerToPixel < ActiveRecord::Migration
def change
rename_table :banner, :pixels
end
end
|
class AdjustReportDesignSchema < ActiveRecord::Migration[5.2]
def change
at = DynamicAnnotation::AnnotationType.where(annotation_type: 'report_design').last
unless at.nil?
json_schema = at.json_schema.clone.with_indifferent_access
options_schema = json_schema[:properties][:options][:items]
j... |
require 'rails_helper'
RSpec.describe User, :type => :model do
describe "Validations" do
it { should validate_presence_of(:provider) }
it { should validate_presence_of(:uid) }
it { should validate_uniqueness_of(:uid).scoped_to(:provider) }
end
describe "Relations" do
it { should have_many(:car... |
require 'spec_helper'
describe MergeController do
let(:master) { FactoryGirl.create(:contact) }
let(:duplicate) { FactoryGirl.create(:contact) }
before(:each) do
login
end
describe "GET merge contact 1 into 2" do
it do
get :into, :klass_name => 'contact', :duplicate_id => duplicate.id... |
#!/usr/bin/ruby
require 'fileutils'
require 'PipelineHelper'
# Class that encapsulates the experiment directory - where corresponding
# GERALD directory(ies) are created.
# Author - Nirav Shah niravs@bcm.edu
class ExptDir
def initialize(fcName)
@fcName = fcName
@pipelineHelper = PipelineHelper.new
... |
log "
*****************************************
* *
* Recipe:#{recipe_name} *
* *
*****************************************
"
vglist=node[:clone12_2][:machprep][:newvgs]
# triplets of file system spac... |
class PokemonAttack < ActiveRecord::Base
validates :Attack, presence: true
validates :Pokemon, presence: true
belongs_to :attack
belongs_to :pokemon
end
|
class Company < ApplicationRecord
has_many :clients
has_many :agents
end
|
# encoding: utf-8
require 'csv'
require_relative '../lib/pile/header.rb'
include Pile
require_relative 'spec_helper'
describe Header, 'column_index' do
include Pile::Helpers
it 'should return the same integer indices' do
header = new_example_header
header.column_index(2).should == 2
header.column_... |
# Adding tracking_status to Trainee model
# tracking_status is used to enable and disable tracking for a specific trainee
class AddingTrackingStatusToTrainee < ActiveRecord::Migration[5.1]
def change
add_column :trainees, :tracking_status, :integer, default: 0
end
end
|
# The "AwesomeObject" class is the central object of our runrime.
# Since everthing is an object in our language,
# everything we will put in the runtime needs to be an object, thus an instance of this class.
# "AwesomeObject"s have a class and can hold a ruby value.
# This will allow us to store data such as a string ... |
class CreateGameEvents < ActiveRecord::Migration
def self.up
create_table :game_events do |t|
t.integer :game_id
t.integer :user_id
t.text :description
t.timestamp :created_at
end
add_index :game_events, :game_id
add_index :game_events, :user_id
end
def self.down... |
class AddColumnScheduledDateToDeliveryOrderDetails < ActiveRecord::Migration
def change
add_column :delivery_order_details, :scheduled_date, :date
end
end
|
class AddUsersTestsQuestionsCategoriesAnswersNullConstraints < ActiveRecord::Migration[6.0]
def change
change_column_null(:answers, :question_id, false)
change_column_null(:categories, :name, false)
change_column_null(:questions, :content, false)
change_column_null(:questions, :test_id, false)
cha... |
class SessionsController < ApplicationController
before_filter :authenticate_user, :only => [:home]
before_filter :forward_when_logged_in, :only => [:login]
layout :get_layout
def login
if params.has_key? :login
authorized_user = User.authenticate(params[:login][:username], params[:login][:password... |
module ApiResponse
def json_response(object, status = :ok, serializer = nil, options = {})
render json: serialized_response(object, serializer, options), status: status
end
def handle_response(data, status, options = {})
json_response(data, status, serializer_class, options)
end
def error_response(e... |
class AddDefaultValueToWorkorder < ActiveRecord::Migration
def up
change_column :workorders, :tk_approval, :boolean, :default => false
change_column :workorders, :mandatory, :boolean, :default => false
change_column :workorders, :action_taken, :boolean, :default => false
change_column :workorders, :in... |
class Plan < Ohm::Model
include Ohm::Timestamping
MEMORY = {
"regular" => "200mb",
"double" => "500mb",
"large" => "1000mb"
}
attribute :type
attribute :uuid
index :type
index :uuid
reference :user, User
def self.start(user, type)
raise ArgumentError unless MEMORY.has_key?(type... |
# == Schema Information
#
# Table name: invitations
#
# id :integer not null, primary key
# course_id :integer
# user_id :integer
# email :string
# created_at :datetime not null
# updated_at :datetime not null
# slug :string
# accepted :boolean default(... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
if Vagrant.has_plugin?("vagrant-cachier")
config.cache.scope = :box
end
# A Ubuntu Trusty machine for smoke testing this module.
config.vm.define "smoketest", primary: true do |... |
class ChangeWorkerCountInUserWorkerTable < ActiveRecord::Migration[5.1]
def change
change_column :user_workers, :worker_count, :integer, null: false, default: 0
end
end
|
require 'givdo/facebook/paginated_connections'
module Givdo
module Facebook
USER_FIELDS = [:name, :email, :cover]
class Friends < PaginatedConnections
def initialize(graph, params)
super graph, 'friends', params.merge(fields: USER_FIELDS)
end
def users
@users ||= Givdo::Fa... |
require 'spec_helper'
describe Post do
before do
@valid_post = Post.new(:title => 'First title', :content => 'first content')
@empty_title_post = Post.new(:title => '', :content => 'first content')
@valid_child = @valid_post.posts.new(:title => 'First child title', :content => 'first child content')
en... |
class Notification < ActiveRecord::Base
# attr_accessible :comment_id, :code, :read, :from_id, :product_id
belongs_to :sender, foreign_key: :from_id, class_name: 'User'
belongs_to :recipient, foreign_key: :to_id, class_name: 'User', inverse_of: :notifications
belongs_to :product
scope :unread, where(read: fa... |
require 'spec_helper'
describe Game do
describe 'Associations' do
it { should have_many(:users).through(:participations) }
it { should have_many(:rounds) }
end
describe '#invite_player' do
it 'creates a participant if the given user was not already on the list' do
game = create(:game)
us... |
require 'spec_helper'
Route = -> (*args) {
Struct.new(:name, :verb, :requirements, :irrelevant) do
def app; OpenStruct.new(dispatcher?: true) end
def path; OpenStruct.new(spec: '/path(.:format)') end
def parts; [] end
end.new(*args)
}
RSpec.describe PryRailsDiffRoutes::RouteWrapper do
let(:first) {... |
describe EhjobAuthentication::UrlExtractorService do
subject { EhjobAuthentication::UrlExtractorService }
let(:local_user) do
user = User.create(email: 't@gmail.com', password: 'password')
user.stub(:highest_role).and_return local_highest_role
user.stub(:terminated).and_return terminated
user.ensur... |
class Program < ActiveRecord::Base
belongs_to :kit
belongs_to :current_step, foreign_key: :step_id, class_name: "Step"
belongs_to :user
has_many :snapshots
validates :kit, presence: true
default_scope :order => 'programs.updated_at DESC'
before_create :set_current_step
before_save :set_name
after_sav... |
module ApplicationHelper
def pusher_include_tag(version)
domain = if request.ssl?
'https://d3dy5gmtp8yhk7.cloudfront.net'
else
'http://js.pusher.com'
end
javascript_include_tag "#{domain}/#{version}/pusher.min.js"
end
end
|
require 'tempfile'
require 'delegate'
module Machsend
module RPC
class Message
class BufferedIO < DelegateClass(IO)
FILE_BUFFER = 4096
attr_reader :io
def initialize(io)
@io = io
super(@io)
end
def read_I16
dat = io.rea... |
require 'time'
require 'grape'
module Janus
module Server
class API < Grape::API
@@statuses =
5.times.map do |i|
{id: i+1, sent_at: Time.parse("2017-02-13T22:1#{3+i}:53Z").iso8601}
end
version 'v1', using: :header, vendor: 'janus'
format :json
prefix :api... |
require 'rails_helper'
RSpec.describe Favorite, type: :model do
before do
@favorite = FactoryBot.build(:favorite)
end
describe 'お気に入り登録' do
context 'お気に入り登録できる' do
it 'ユーザー、投稿に紐づいていれば登録できる' do
expect(@favorite).to be_valid
end
end
context 'お気に入り登録できない' do
it 'ユーザーに紐づいてい... |
namespace :neighbors do
desc "Print neighbor stats"
task :stats do
# find cities by density
density = 25000
cities = City.min_density(density).order_by_density
puts "#{Time.now}: found #{cities.size} cities with more than #{density} locations"
cities.each do |city|
# use the :g... |
#def running_total(num_array)
# sum = 0
# num_array.map { |num| sum += num }
#end
def running_total(num_array)
new_array = []
num_array.each_with_index { |_, idx| new_array << num_array[0..idx].sum }
new_array
end
p running_total([2, 5, 13])
p running_total([14, 11, 7, 15, 20])
p running_total([3])
|
class LogsController < ApplicationController
def index
@title = "Logs Index"
@logs = Log.order("id DESC")
end
def show
@log = Log.find(params[:id])
@title = "Show log ID #{@log.id}"
end
end
|
describe 'Adapter' do
include_context 'container'
before do
configuration.relation(:users) do
adapter :redis
def by_id(id)
hgetall(id)
end
end
configuration.mappers do
define(:users) do
model User
end
end
end
it 'works' do
rom.relations.users... |
module Merit::Models::ActiveRecord
class BadgesSash < ActiveRecord::Base
include Merit::Models::BadgesSashConcern
has_many :activity_logs,
class_name: 'Merit::ActivityLog',
as: :related_change
validates_presence_of :badge_id, :sash
end
end
class Merit::BadgesSash < Merit::Mo... |
class Api::V1::BaseController < ActionController::API
respond_to :json
before_action :doorkeeper_authorize!
private
def current_user
if params['user_id']
@current_user ||= User.find_by id: params['user_id']
else
nil
end
end
end
|
# case (como el switch en java)
# Notas van de 0 al 10; 5 es suspendido
print "Dame tu calificacion (1-10): "
calificacion = gets.chomp.to_i
# El método que se usa, hace la comparación vía ===
puts case calificacion
when 10, 9
"Muy bieeeeen"
when 8
"Bien, pero puedes mejorar"
when 7
"Sabemos que lo puede... |
require 'json'
require 'open-uri'
require 'faraday'
require 'fileutils'
class UpdateSlackEmoji
include Interactor
SLACK_TOKEN = ENV.fetch('SLACK_USER_TOKEN')
def call
endpoint = "https://slack.com/api/emoji.list?token=#{SLACK_TOKEN}"
res = JSON.parse(Faraday.get(endpoint).body)
dirname ... |
Vagrant.configure("2") do |config|
config.trigger.after :up do |trigger|
trigger.info = "Copying generated certificates from bootstrap controller..."
trigger.only_on = "controller-1"
trigger.run = { path: "scripts/get-certs.sh" }
end
# Kubernetes Controllers
(1..3).each do |i|
config.vm.define... |
require 'spec_helper'
module Binged
module Search
describe "Video" do
include AnyFilter
include AnyPageable
before(:each) do
@client = Binged::Client.new(:account_key => 'binged')
@search = Video.new(@client)
end
it "should initialize with a search term" do
... |
require 'rails_helper'
RSpec.describe Rating, type: :model do
before(:each) do
@user = User.create(login: 'akxcv')
@post = Post.create(user: @user, title: 'Hello',
content: 'hello', ip: '192.168.1.4')
end
it 'belongs to a post' do
bad_rating = Rating.create(post: nil, value: ... |
class Device < ActiveRecord::Base
validates_presence_of :name
has_one :user
def in?
!user
end
def out?
!!user
end
end
|
# Brack order routines
#
require 'ib-ruby'
# BracketOrder -- place order with corresponding stop and profit orders
#
# See also: https://www.interactivebrokers.com/en/software/webtraderguide/webtrader/orders/supported_order_types.htm
module PryIb
class BracketOrder
attr_accessor :id, :ib, :order_price,:stop_price,... |
class AnswerSerializer < ActiveModel::Serializer
attributes :id, :body, :best, :question_id, :created_at, :updated_at
belongs_to :author
has_many :comments
has_many :files, serializer: AttachmentSerializer
has_many :links
end |
RSpec.describe 'Productions', type: :request do
describe 'PUT /batches/productions/:reference' do
it 'if found, set orders to production' do
batch = create(:batch) do |batch|
create_list(:order, 5, batch: batch)
end
put api_v1_batches_production_path(batch.reference)
json_respons... |
FactoryBot.define do
factory :ring_group do
name { Faker::Job.title }
factory :ring_group_with_number do
number factory: :phone_number
end
end
end
|
class CitiesController < ApplicationController
def index
@city = City.new
@cities = City.all.paginate(page: params[:page], per_page: 8)
end
def create
@city = City.new(city_params)
if @city.save
DumperWorker.perform_async(@city.id)
flash[:success] = 'City saved successfully, scraping... |
class CategoryImageUploader < AttachmentUploader
process :resize_to_fit => [450, 300]
def extension_white_list
%w(jpg jpeg png)
end
end
|
[1, 2, 3].any? do |num|
puts num
num.odd?
end
# the blocks return value is true. it is determined because
# the last line returns num.odd? as their is an odd number, it will return true
# the return value of any? in this code is true
# as the blocks return value is true, so will any (if the block returned... |
module EasyAuth
class Feature < ActiveRecord::Base
has_and_belongs_to_many :roles
scope :by_authorizable, -> (authorizable_id) {
joins(:roles).merge(Role.by_authorizable(authorizable_id))
}
scope :by_group, -> (group_id) {
joins(:roles).merge(Role.by_group(group_id))
}
end
end
|
class PregnancyNotesController < ApplicationController
before_action :authenticate_doctor!
before_action :set_gynecology_template
before_action :authenticate_doctor_for_gynecology_template
before_action :set_pregnancy_note, only: [:show, :edit, :update, :destroy]
def new
@note = @gynecology_template.pregnancy_n... |
KepplerGaDashboard::Engine.routes.draw do
get '/', to: 'dashboard#analytics'
end
|
class PicturesController < ApplicationController
before_action :set_picture, only: [:show, :edit, :update, :destroy]
LINDA_EMAIL = "lindabrams@yahoo.com"
# GET /pictures
def index
@title = 'Photo Gallery'
pictures = Picture.where.not(:year => 9999).order(:year => :desc).all
@pictures_by_year = {}
... |
# Toegangsbewijs model
class Toegangsbewijs < ActiveRecord::Base
require 'barcode'
belongs_to :klant
belongs_to :artefact
after_create :create_barcode
# Een volwassenen (18 t/m 59 jaar) kost 4,-
# Een jongeren (12 t/m 17) kost 2,50
# Een ouderen (60+) kost 2,50
# Kinderen zijn gratis
def calculeer_... |
module ApplicationHelper
LOOKUPS = [PhoneType, ClearanceLevel, Branch, Rank, ClearanceLevel, CustomerName, Position,
ProjectType, State, Certification, ApprovedStatus, Degree, TravelAuthorization].freeze
# Determines if we're in a development type environment
#
# Returns true for following environ... |
# == Schema Information
#
# Table name: comments
#
# id :integer not null, primary key
# comment :text
# score :integer
# created_at :datetime not null
# updated_at :datetime not null
# event_id :integer
# person_id :integer
#
#Created by : Tarika Bedse
... |
# Attachment:
#
# title, string
# locale, string
#
# file, carrierwave file
# file_meta, hash, keys - size, mime-type [, width, height].
#
# attachable_type, string
# attachable_id, integer
#
# created_at, datetime
#
class Attachment
include Mongoid::Document
include Mongoid::Timestamps
# be... |
require_relative '../rails_helper'
# Prefix instance methods with a '#'
describe Piece do
context '#primary_tag' do
it 'correctly updates primary tag' do
piece = create(:piece)
tag = 'primary_tag'
piece.primary_tag = tag
expect(piece.primary_tag).to eq(tag)
end
it 'returns nil w... |
# frozen_string_literal: true
# https://adventofcode.com/2019/day/1
require 'pry'
require './boilerplate'
def fuel_for_mass(mass, recurse = false)
fuel = (mass / 3).floor - 2
return 0 if fuel < 0
return (fuel + fuel_for_mass(fuel, true)) if recurse
fuel
end
def fuel_for_modules(modules, recurse = false)
mo... |
require "rails_helper"
feature "Account" do
scenario "user without Stripe Customer ID" do
user = create(:user, stripe_customer_id: nil)
sign_in_as(user)
visit account_path
expect(page).not_to have_text("Update Credit Card")
end
scenario "user with Stripe Customer ID" do
stripe_customer_id ... |
class Panel::CuisinesController < Panel::BaseController
before_action :set_cuisine, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@cuisines = Cuisine.all.order('name')
end
def new
@cuisine = Cuisine.new
end
def edit
end
def create
@cuisine = Cuisine.new(cuisine_par... |
require "application_system_test_case"
class SignupsTest < ApplicationSystemTestCase
test "teste de cadastro de usuário" do
visit root_path
click_on "Cadastre-se"
fill_in "Nome", with: "Renato Soares"
fill_in "E-mail", with: "teste@teste.com"
fill_in "Senha", with: "teste@123"
fill_in "Con... |
class Message < ApplicationRecord
# GEM PARANOIA
acts_as_paranoid
# END GEM PARANOIA
# VALIDATIONS AND ASSOCIATIONS
belongs_to :stay
validates :content, presence: true
validates :from, presence: true
# END VALIDATIONS AND ASSOCIATIONS
# MESSAGE LIST
MESSAGE = {
wifi_network: "Our WIFI netwo... |
module CollinsNotify
class Configuration
include CollinsNotify::ConfigurationMixin
attr_reader :logger
attr_accessor :adapters
def initialize logger, opts = {}
@adapters = {}
configurable.each do |key, value|
instance_variable_set "@#{key.to_s}".to_sym, value
end
@lo... |
class H0200a
attr_reader :options, :name, :field_type, :node
def initialize
@name = "Urinary Toileting Program: Has a trial of a toileting program (e.g., scheduled toileting, prompted voiding, or bladder training) been attempted on admission/entry or reentry since urinary incontinence was noted in this facilit... |
require_relative 'helper'
require_relative '../lib/gutenberg/html_supervisor.rb'
describe Gutenberg::HTMLSupervisor do
describe "#initialize" do
it "can retrieve the book used upon creator" do
Gutenberg::Book.stubs(:new).returns(mock('book'))
Gutenberg::HTMLSupervisor.new(Gutenberg::Book.new)
end... |
class RemoveEmailToEmployeeAuths < ActiveRecord::Migration[6.1]
def change
remove_index :employee_auths, :email
remove_column :employee_auths, :email, :string
end
end
|
sides_of_the_dice = *(1..6)
number_of_dice = 2
#Create the hash necessary
totals = []
permutations = {}
#Populate the hash with numbers 2 to 12
(2..12).each do |number|
permutations[number] = 0
end
puts "The permutations before calculation"
puts permutations
#Calculate two dice roll totals if permutations are rol... |
class AddIndexes < ActiveRecord::Migration
def change
add_index :menu_items, :restaurant_id
add_index :menu_items_tags, [:menu_item_id, :menu_tag_id], unique: true
end
end
|
module Collins
class Ipmi
include Collins::Util
attr_accessor :address, :asset_id, :gateway, :id, :netmask, :password, :username
def self.from_json json
Collins::Ipmi.new json
end
def initialize opts = {}
hash = symbolize_hash(opts).inject({}) do |result, (k,v)|
key = k.to... |
module BakerServer
class Issue < ActiveRecord::Base
validates_presence_of :issue_id
validates_presence_of :published_date
validates_presence_of :summary
validates_length_of :summary, :maximum => 2000
validate :published_date_order
image_accessor :cover_art
protected
def published_dat... |
module RobotSimulator
class Right
RIGHT_DIRECTION_MAPPING = {'NORTH' => 'EAST', 'EAST' => 'SOUTH', 'SOUTH' => 'WEST', 'WEST' => 'NORTH'}
def initialize(robot)
@robot = robot
end
def execute
@robot.position.direction = RIGHT_DIRECTION_MAPPING[@robot.position.direction] if @robot.is_placed?... |
require './src/tokenizer/lexer'
require './src/tokenizer/errors'
require './spec/contexts/lexer'
RSpec.describe Tokenizer::Lexer, 'error handling' do
include_context 'lexer'
describe '#next_token' do
it 'raises an error for an invalid loop iterator particle' do
mock_reader(
"「永遠」を 対して 繰り返す\n"
... |
require 'spec_helper'
describe Omniauth::Elcurator do
describe 'VERSION' do
it { expect(Omniauth::Elcurator::VERSION).not_to be nil }
end
end |
require 'spec_helper'
describe UploadResumesController do
describe 'routing' do
it 'routes to upload_resumes#new' do
get('/consultants/1/upload_resumes/new').should route_to('upload_resumes#new',
consultant_id: '1')
end
it 'routes to ... |
class ContentController < Spree::BaseController
rescue_from ActionView::MissingTemplate, :with => :render_404
caches_page :show, :index, :if => Proc.new { Spree::Config[:cache_static_content] }
def show
render :action => params[:path].join('/')
end
def cvv
render "cvv", :layout => false
end
en... |
# frozen_string_literal: true
class FileSetDerivativeFailureJob < FileSetAttachedEventJob
def action
"The derivative for #{link_to repo_object.title.first, polymorphic_path(repo_object)} was not successfully created"
end
end
|
require 'active_support/concern'
module Searchable
extend ActiveSupport::Concern
module ClassMethods
attr_reader :search_fields
private
def searchable(*search_fields)
@search_fields = search_fields
end
end
included do
def self.search(term = nil)
return all if term.blank?
... |
class TissEvaluation < ApplicationRecord
belongs_to :patient
belongs_to :user
resourcify
before_save :obtain_score
validates :user_id,
presence: true
validates :evaluation_date,
presence: true,
uniqueness: { scope: [:patient_id], message: "already-has-evaluation" }
scope :yesterday, -> { wh... |
class AddServiceTypeToJob < ActiveRecord::Migration
def change
add_column :jobs, :service_type, :string
add_column :jobs, :recycling_notes, :text
add_column :jobs, :recycling_weight, :integer
end
end
|
require 'pry'
languages = {
:oo => {
:ruby => {
:type => "interpreted"
},
:javascript => {
:type => "interpreted"
},
:python => {
:type => "interpreted"
},
:java => {
:type => "compiled"
}
},
:functional => {
:clojure => {
:type => "compiled"
... |
class ApplicationController < ActionController::Base
layout 'home'
protect_from_forgery
before_filter :set_global_search_variable
def set_global_search_variable
@q = Product.search(params[:q])
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... |
require 'rails_helper'
RSpec.describe 'Api::V1::BikeController', type: :request do
let!(:bike) { Bike.create(model: 'M123') }
let(:bike_id) { bike.id }
describe "GET api/v1/bikes/:bike_id" do
before do
get "/api/v1/bikes/#{bike_id}"
end
it 'returns http :ok' do
expect(response.status... |
class StoneOven
attr_reader :state, :temperature
def initialize(temperature: 320, state: :on)
@state = state
@temperature = temperature
end
def bake(pizza)
raise IOError.new("Oven is not hot enough") unless can_bake?
Log.info "Baking the pizza"
sleep 2
Log.info "Pizza is now ready"
... |
require 'test_helper'
class EventToSponsorsControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:event_to_sponsors)
end
test "should get new" do
get :new
assert_response :success
end
test "should create event_t... |
require_relative '../lib/game_of_life'
require_relative '../lib/cell'
require 'colorize'
class Grid
def print_results(game_of_life)
board_layout = Array.new(10).map { |_row| Array.new(10, "|_|".bold.yellow) }
game_of_life.live_cells.each do |c|
board_layout[c.row][c.column] = "|X|".bold.blue
... |
# frozen_string_literal: true
# Copyright © 2019-2021 Ismo Kärkkäinen
# Licensed under Universal Permissive License. See LICENSE.txt.
require 'json'
require 'open3'
class DatalackeyProcess
attr_reader :exit_code, :stdout, :stderr, :stdin, :executable
def initialize(exe, directory, permissions, memory)
@exit... |
class ReportsController < ApplicationController
before_action :set_report, only: %i[show destroy data]
# GET /reports/1
def show
render json: @report
end
# POST /reports
def create
@dataset = Dataset.new(dataset_params)
@report = Report.new(dataset: @dataset)
if @report.save
render j... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.