text stringlengths 10 2.61M |
|---|
Puppet::Type.newtype(:zbx_hostgroup) do
desc 'zbx_hostgroup is used to manage the Hostgroups configured in your Zabbix server'
ensurable
newparam(:name, :namevar => true) do
desc 'The name of the Zabbix Hostgroup'
end
newproperty(:groupid) do
desc 'The read-only Groupid of the Zabbix Hostgroup'
... |
class Asteroids::Game < Gamey::Game
title 'Asteroids'
resolution width: 800, height: 600
controls({
forward: [Gosu::KbUp, Gosu::KbW],
left: [Gosu::KbLeft, Gosu::KbA],
right: [Gosu::KbRight, Gosu::KbD],
start_game: [Gosu::KbSpace],
shoot: [Gosu::KbSpace]
... |
class CreateEntriesTable < ActiveRecord::Migration
def change
create_table :entries do |t|
t.string :header, :limit => 1000
t.string :post, :limit => 5000
t.string :date_created
t.timestamps
end
end
end |
require 'gosu'
require_relative 'tile'
class Player < Tile
attr_reader :score
def initialize(window, column, row)
super(window, column, row, Tile::PLAYER_TYPE)
@score = 0
end
def pick_up(tile)
if tile.is_treasure?
@score += 1
tile.make_empty
end
end
end
|
class Assignment < ApplicationRecord
belongs_to :user
belongs_to :task
before_create :capture_task_status
private
def capture_task_status
self.task_status ||= task.status
end
end
|
class AddSeparatedRatingsToUsers < ActiveRecord::Migration[5.0]
def change
rename_column :users, :rating, :artist_rating
change_column :users, :artist_rating, :float, default: 0.0
add_column :users, :commissioner_rating, :float, default: 0.0
end
end
|
class User < ActiveRecord::Base
extend FriendlyId
friendly_id :username
before_validation { self.username = username.downcase }
validates :username, presence: true, uniqueness: true, length: { maximum: 50 }
validates_format_of :username, :with => /\A[a-z0-9]+\z/i
validates :email, presence: true
validates... |
class RecommendationsController < ApplicationController
def index
if params[:subtopic].to_s.strip.blank?
@error = "Please provide a subtopic parameter: '/recommendations?subtopic=X' or paste the subtopic into the search field above."
end
unless SubTopic.where(subtopic_id: params[:subtopic]).exists?
... |
class Animal
attr_accessor :name, :fuzziness
def initialize(name, fuzziness)
unless name.is_a?(String) && fuzziness.between?(0, 5)
raise "name has to be a string and fuzziness has to be 1 - 10."
@name, @fuzziness = name, fuzziness
end
end
end
class Bird < Animal
def eggs(number)
number.... |
# frozen_string_literal: true
class YhPicturesController < ApplicationController
before_action :set_yh_picture, only: %i[show edit update destroy taken]
# GET /yh_pictures
# GET /yh_pictures.json
def index
@q = YhPicture.search(params[:q])
@yh_pictures = @q.result
if params[:q]
session[:curr... |
class DatapointsController < ApplicationController
before_filter :get_tracker
respond_to :json
def create
respond_with @tracker.datapoints.create!(datapoint_params), location: ''
end
private
def datapoint_params
params.require(:datapoint).permit!
end
def get_tracker
@tracker = current_us... |
class Api::V1::AutomaticsController < Api::V1::ApiController
version 1
before_action :set_automatic, only: [:show]
def index
@automatics = Automatic.page(params[:page])
expose @automatics
end
def show
expose @automatic
end
def create
@automatic = Automatic.new(trip: automatic_params)... |
require 'spec_helper'
describe 'heat::cache' do
let :params do
{}
end
shared_examples_for 'heat::cache' do
context 'with default parameters' do
it 'configures cache' do
is_expected.to contain_oslo__cache('heat_config').with(
:config_prefix => '<SERVICE DE... |
require 'rails_helper'
RSpec.describe "form_responses/edit", type: :view do
before(:each) do
@form_response = assign(:form_response, FormResponse.create!(
:form => nil
))
end
it "renders the edit form_response form" do
render
assert_select "form[action=?][method=?]", form_response_path(@f... |
class User < ActiveRecord::Base
has_merit
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :registerable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
# Setup acce... |
# Absolute paths
# use forward slashes, even on windows
puts "/var/www/Ruby-Essentials/sandbox/chapter_08"
# File.join ensures platform dependencies
# absolute path is made by passing an empty string as first argument
puts File.join('', 'var', 'www', 'Ruby-Essentials', 'sandbox', 'chapter_08')
# Relative paths
# __FI... |
class CompaniesController < ApplicationController
def new
@company = Company.new
end
def create
@company = Company.new(company_params)
if @company.save
redirect_to @company, notice: 'Company was successfully created.'
else
redirect_to "/"
end
end
def show
@company = curre... |
module SmsBroker
module Client
class Twilio < Base
def initialize(options)
client = \
::Twilio::REST::Client.new(options[:account_sid], options[:auth_token])
super :Twilio, client, options
end
def send_message(message)
begin
response = client.messa... |
class CreateRestaurantCategorizations < ActiveRecord::Migration
def change
create_table :restaurant_categorizations do |t|
t.references :restaurant, index:true
t.references :restaurant_specialty, index:true
t.timestamps
end
end
end
|
class BillsController < ApplicationController
# @description Creates new Bill
# @param bill[bill_type] required String Can be one of:
# parking_ticket, water_bill, vehicle_ticket
# @param bill[status] required String Can be one of:
# paid, unpayed
# @param bill[payment_status] required String Can be one of... |
require 'rails_helper'
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
RSpec.describe MoviesController, type: :controller do
movies_data = [
{:title => 'Star Wars', :rating => 'PG', :director => 'George Lucas', :release_date => '1977-05-25'},
{:title => 'Blade Runner', :rating => 'PG',... |
# encoding: UTF-8
require 'highline/import'
require 'multi_json'
require_relative '../cli/terminal'
require_relative '../helpers/helpers'
module GoodData
module Command
class Auth
class << self
# Get path of .gooddata config
def credentials_file
"#{GoodData::Helpers.home_directo... |
require 'open-uri'
$LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib"
require 'web_parser'
class YahooSearch
# include WebParser
include WebParser::Doc
# define recipes
recipes do
# simplest way to define recipe
query :xpath, '//input[@id="yschsp"]/@value'
# You can use simple normaliz... |
# frozen_string_literal: true
class Company < ApplicationRecord
has_many :users
end
|
FactoryBot.define do
factory :warranty do
asset factory: :item
length { Faker::Number.digit }
end
end
|
class Admin::MoviesController < Admin::BaseController
include Flexigrid
crudify
def index
@resource_columns = "
{display:'ID' ,name:'id' ,width:25,sortable:true ,align:'left',hide:false},
{display:'Titulo' ,name:'title' ,width:400,sorta... |
class GenerateReportPdf
def self.export_pdf(model, method, parameters, opts)
pdf_report=AdditionalReportPdf.find_by_model_name_and_method_name(model,method)
if pdf_report.nil?
pdf_report=AdditionalReportPdf.new(:model_name=>model,:method_name=>method,:parameters=>parameters, :status => true, :opts =... |
PASSWORDS = INPUT.split("\n").map(&:split)
def valid_count(passwords)
passwords.count do |words|
words.none? { |word| words.count(word) > 1 }
end
end
solve!("Number of valid passwords:", valid_count(PASSWORDS))
DEANAGRAMIZED_PASSWORDS = PASSWORDS.map { |row| row.map { |word| word.chars.sort.join } }
solve!(... |
#
# Cookbook Name: ubercloud
# Recipe:: dockerd.rb
#
yum_repository 'docker-ce' do
description 'Docker Repository'
baseurl 'https://download.docker.com/linux/centos/7/$basearch/stable'
gpgcheck false
action :create
end
yum_package 'device-mapper-persistent-data' do
action :install
end
yum_package 'docker-ce... |
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
def camelcase
self.split(/(?=[A-Z])|(_)/)
.reject { |e| e == '_' }
.map(&:capitalize)... |
class CreateCompanies < ActiveRecord::Migration[5.0]
def change
create_table :companies do |t|
t.string :company_name
t.text :company_address
t.string :contact_no
t.string :company_reference
t.decimal :previous_amount
t.decimal :net_balance
t.decimal :received_amount
... |
class WholeNumber < ActiveRecord::Base
attr_accessible :value
def to_s
value.to_s
end
def to_html
value.to_s
end
end
|
class Neovim < Formula
desc "Ambitious Vim-fork focused on extensibility and agility"
homepage "https://neovim.io/"
url "https://github.com/neovim/neovim/archive/v0.2.2.tar.gz"
sha256 "a838ee07cc9a2ef8ade1b31a2a4f2d5e9339e244ade68e64556c1f4b40ccc5ed"
revision 1
head "https://github.com/neovim/neovim.git"
... |
FactoryBot.define do
factory :ingredient do
sequence(:name) {|n| " name ingredient #{n}" }
calories { "130" }
trait :invalid do
name { nil }
end
trait :new_name do
name { 'New ingredient' }
end
end
end
|
class Report
PADDING = -10
def self.from_hash(currencies)
formatter = -> curr { "#{curr}: %<#{curr}>#{PADDING}s" }
report = ""
currencies.each do |pair|
report.concat formatter.call(pair[0])
end
puts report % currencies
end
end
|
# docs: http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html#searching
# example: http://itunes.apple.com/search?term=angry+birds&media=software
class Search::ItunesSearch
extend LoggerModule
include HTTParty
base_uri 'itunes.apple.com'
def self.for(query, ... |
class CreateProblems < ActiveRecord::Migration
def change
create_table :problems do |t|
t.integer :course_id, null: false
t.string :name
t.string :description
t.integer :submit_num, default: 0
t.integer :status, default: 1 # default: reviewing
t.boolean :is_example, default: f... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
require 'pry'
# I'm going to be using a few different methods to be able to get and/or set the value of an instance object of the Robot class:
# 1. attr_accessor - Any attributes I want to be able to get and/or set from OUTSIDE the class, I'll pass into the attr_accessor method.
# 2. @instance_variables - Any variab... |
class ForgotName < ActiveRecord::Migration
def change
add_column :eorowcols, :name, :string
end
end
|
class HomeController < ApplicationController
def index
@gallery = Gallery.order('RANDOM()').limit(32)
@banners = Banner.order(:position)
@tour_program = TourProgram.order(:position)
@registration = Registration.new
end
end
|
# frozen_string_literal: true
FactoryBot.define do
factory :comment do
content { 'MyText' }
user_id { 1 }
play_id { 1 }
end
end
|
require 'spec_helper'
describe "Users" do
describe "GET /" do
it "should display a login page" do
visit root_path
expect(page).to have_content 'Log in'
end
end
end
|
# '<': INHERITING BEHAVIOUR
# The following is an example of an inheritance relationship between two classes:
class Animal
def initialize
puts "initialize instance method defined in Animal was called"
end
def speak
puts "speak instance method defined in Animal class was called"
end
end
class Cat < A... |
class PenaltiesController < ApplicationController
def create
list = List.find(params[:list_id])
if params[:penalty][:name].blank? or params[:penalty][:amount].blank?
head 400
return
end
penalty = list.penalties.create(chore_params)
notify_email = list.notifications.where(:role=>'chore... |
module ApplicationHelper
def websites_list_caption
current_user.admin? ? 'Manage websites' : 'My websites'
end
end
|
require File.dirname(__FILE__) + '/../spec_helper'
describe EspecialistasController do
describe "route generation" do
it "should map { :controller => 'especialistas', :action => 'index' } to /especialistas" do
route_for(:controller => "especialistas", :action => "index").should == "/especialistas"
end... |
class Cposting < ActiveRecord::Base
include PgSearch
multisearchable :against => [:title, :content]
extend SimpleCalendar
has_calendar attribute: :starts_at #uses starts_at (default) column as value
belongs_to :user
has_many :subscriptions,
foreign_key: "post_id",
dependent: :destroy
defaul... |
require 'astrails/safe/config/builder'
module Astrails
module Safe
module Config
class Node
attr_reader :parent
def initialize(parent = nil, data = {}, &block)
@parent, @data = parent, {}
data.each { |k, v| self[k] = v }
Builder.new(self).instance_eval(&block) i... |
class Country < ApplicationRecord
has_many :leagues
accepts_nested_attributes_for :leagues
end
|
module Roglew
module GL
CLAMP_FRAGMENT_COLOR_ARB||= 0x891B
CLAMP_READ_COLOR_ARB ||= 0x891C
CLAMP_VERTEX_COLOR_ARB ||= 0x891A
FIXED_ONLY_ARB ||= 0x891D
RGBA_FLOAT_MODE_ARB ||= 0x8820
end
end
module GL_ARB_color_buffer_float
module RenderHandle
include Roglew::RenderHandleE... |
class TimelinesController < ApplicationController
before_filter :require_auth
before_filter :set_cache_headers, :only => [:index]
# GET /timelines.format
def index
respond_to do |format|
format.html
format.json {
timeline = current_user.yearly_timeline
render :json => timeline
... |
require 'spec_helper'
describe Mist::Configuration do
subject { Class.new { include Mist::Configuration }.new }
it "should have a default repo location" do
subject.repository_location.should_not be_blank
subject.repository_location.should == subject.default_repository_location
end
it "should allo... |
require "test_helper"
require "rails/generators/test_case"
require "generators/pointless_feedback/views_generator"
class ViewsGeneratorTest < Rails::Generators::TestCase
tests PointlessFeedback::Generators::ViewsGenerator
destination File.expand_path("../../tmp", __FILE__)
setup :prepare_destination
test "Ass... |
#!/usr/bin/env ruby
require 'rest-client'
require 'optparse'
require 'yaml'
Options = Struct.new(:server,:username,:password,:yaml)
class Parser
def self.parse(options)
args = Options.new()
args.server="localhost:9393"
args.yaml = "streams.yml"
opt_parser = OptionParser.new do |opts|
opt... |
require "rails_helper"
RSpec.feature "User", type: :feature do
let!(:company) { Company.create!(name: "acme",
information: "asdf") }
let!(:job) { company.jobs.create!(title: "Job1",
description: "Job 1 description") }
let!(:job2) { company.jo... |
require "application_system_test_case"
class PSpacesTest < ApplicationSystemTestCase
setup do
@p_space = p_spaces(:one)
end
test "visiting the index" do
visit p_spaces_url
assert_selector "h1", text: "P Spaces"
end
test "creating a P space" do
visit p_spaces_url
click_on "New P Space"
... |
module Api
module V1
class PhrasesController < ApplicationController
def setup
phrase = Phrase.all.order(:day)
start_date = phrase.first.day
end_date = phrase.last.day
render json: {start_date: start_date, end_date: end_date}, status: :ok
end
def show
phra... |
describe Domain::RunJob do
describe '#error' do
it 'fires StateChangedToError event' do
run_job = described_class.new('some_uid', 'email')
run_job.error('something went wrong')
expect(run_job.state).to eq('error')
expect(run_job.error_message).to eq('something went wrong')
expect(ru... |
require 'spec_helper'
describe Crypto::PrivateKey do
let (:bobsk) { "]\xAB\b~bJ\x8AKy\xE1\x7F\x8B\x83\x80\x0E\xE6o;\xB1)&\x18\xB6\xFD\x1C/\x8B'\xFF\x88\xE0\xEB" } # from the nacl distribution
let (:bobsk_hex) { Crypto::Encoder[:hex].encode(bobsk) } # from the nacl distribution
let(:bobpk) { "\xDE\x9E\xDB}{}\xC1\... |
require 'test_helper'
class ExtrasTest < Minitest::Spec
class Order < TestModel
attr_accessor :order_number, :total_price, :customer
end
class Customer < TestModel
attr_accessor :first_name, :last_name
end
class OrderSerializer < SimpleJsonapi::Serializer
attribute(:order_number) { |_order| @ov... |
require 'fileutils'
require 'test/unit'
require 'pp'
require 'rubygems'
require 'bundler/setup'
require 'rspec'
require 'json'
require 'data_mapper'
require 'dm-core'
require 'dm-sqlite-adapter'
require 'wikipedia'
require 'vocabularise/queue'
require 'spec/spec... |
class MagazineProduct < ActiveRecord::Base
belongs_to :magazine
belongs_to :product
default_scope { joins(:product).order("products.model_number ASC") }
end
|
class MyRange
attr_reader :value
def initialize(value)
@value = value
end
def succ
MyRange.new(@value + 1)
end
def <=>(other)
self.value <=> other.value
end
end |
class BoardsController < ApplicationController
def index
@boards = Board.all
end
def new
@board = Board.new
end
def create
@board = Board.new(params_board)
if @board.save
redirect_to boards_path, notice: "新增看板成功"
else
render :new
end
end
def edit
@board = Board.find... |
## require 'pry'
class Artist
## add attribute getters and setters
attr_accessor :name
def initialize(name)
## Initialize a new artist with its name
@name = name
## create an empty list for its songs
@songs = []
end
def add_song(song)
## add s... |
Quando('realizar uma requisição para consultar os filmes') do
@response = @films.retrieve_films
end
Entao('armazeno os titulos dos filmes em uma variável') do
titles = @response['results'].map { |film| film['title'] }
expect(@response['count']).to eq(titles.size)
end
Entao('a API deve retornar todos os filmes ... |
# Expected result
# flatten [[1, [8, 9]], [3, 4]] -> [1,8,9,3,4]
def flatten(array,result=[])
array.each do |ele|
if ele.kind_of? Fixnum
result << ele
else
flatten(ele,result)
end
end
result
end
p flatten [[1, [8, 9]], [3, 4]]
|
require 'pry'
=begin
Voici les règles du programme :
le programme est à deux joueurs only (pas d'intelligence artificielle)
le programme doit commencer en demandant le prénom des joueurs
le programme doit afficher le plateau chaque tour (dans le terminal), puis demander au joueur auquel c'est le tour où ce dernier c... |
describe 'Add comment' do
let(:organizer) { create(:user) }
let(:user) { create(:user) }
let(:event) { create(:event, organizer: organizer, start_date: 1.month.from_now, published: true) }
before do
sign_in_user(user)
visit event_path(event)
fill_in('comment_content', with: 'This is a test comment'... |
class DynamoDBLocal
DIST_DIR = File.join(File.dirname(__FILE__), 'DynamoDBLocal-latest')
PIDFILE = "#{DIST_DIR}/dynamodb.pid"
def self.ensure_is_running!
if File.exists? PIDFILE
begin
pid = File.read(PIDFILE).gsub(/\n/,'').to_i
Process.kill(0, pid)
rescue Errno::ESRCH
STDE... |
require 'hashie'
class Fn::Salesforce::Options
def initialize(attributes)
@attributes = attributes
end
def credentials
return @credentials if @credentials
if @attributes[:credentials].is_a? String
attributes = JSON.parse(File.read(@attributes[:credentials]))
else
attributes = @at... |
class TweetParser
attr_accessor :list, :tweets
def initialize
@list = []
@tweets = []
end
def get_list
@list = Twitter.list_timeline("cincy-street-food-vendors")
end
def get_tweets(list)
@list.each do |tweet|
if tweet.geo
@tweets << tweet
break
end
end
... |
class RemoveRestaurantsFromVotes < ActiveRecord::Migration[6.0]
def change
remove_reference :votes, :restaurant, null: false, foreign_key: true
end
end
|
class Character < ActiveRecord::Base
belongs_to :user
belongs_to :campaign
validates :name, presence: true
validates :level, numericality: true
def self.search(params)
where("name LIKE ?", "%#{params}%")
end
end
|
require('capybara/rspec')
require('./app')
Capybara.app = Sinatra::Application
set(:show_exceptions, false)
describe('adding a new doctor', {:type => :feature}) do
it('allows a user to click a doctor to see the patients and details for it') do
visit('/')
click_link('Add New Doctor')
fill_in('name', :with... |
class VideofxesController < ApplicationController
before_action :correct_video, only: [:edit, :upload, :rewrite]
before_action :agree_video, only: [:rewrite]
before_action :reject_true, only: [:upload]
before_action :find_video, only: [:item, :edit, :update, :destroy, :upload, :screenshot, :upvote, :downv... |
namespace :geocoding do
desc 'Given an input CSV of zip codes, print a formatted address'
task :by_zip => :environment do
zips = File.open(ENV['infile'], 'r').readlines
zips.each do |zip|
address_data = Geocoder.search(zip).first.try(:address_data)
next unless address_data
puts "#{ addres... |
require 'big_ml/base'
module BigML
class BatchPrediction < Base
BATCH_PREDICTION_PROPERTIES = [
:category, :code, :created, :credits, :dataset, :dataset_status,
:description, :fields, :dataset, :model, :model_status, :name,
:objective_fields, :prediction, :prediction_path, :private, :resource,
... |
require 'slop'
class Servatron::CLI
def self.start
Slop.parse strict: true, help: true do
banner 'Usage: servatron [options]'
command 'server' do
on 'port=', 'set the port of the server'
on 'app_root=', 'the root directory of your app'
run do |options, args|
app =... |
#encoding: utf-8
module EventsHelper
include ActsAsTaggableOn::TagsHelper
def tags_cloud(*arg)
tags = Event.tag_counts_on(:tags, :limit => 30 )
html = ''
tags.each do |tag|
if params[:tag] == tag.name
html << (content_tag :li, (link_to_tag tag.name), :class => :select)
else
html << ... |
class User < ActiveRecord::Base
has_many :orders
has_many :reviews
has_many :items, through: :orders
has_secure_password
#attr_accessible :email, :password, :password_confirmation, :admin
validates_presence_of :email
validates_presence_of :name
validates_uniqueness_of :email, case_sensitive:... |
class ChargesController < ApplicationController
include ActionView::Helpers::NumberHelper
before_action :authenticate
before_action :set_order, only: [:create]
def create
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken]
)
charge = St... |
class HomeController < ApplicationController
before_action :authenticate_user!, only: [:follow_user]
def index
# @post = Post.new
# @posts = Post.approved.reverse
@communities = Community.limit(8)
if current_user
@community = Community.new
end
@client_token = Braintree::ClientToken.ge... |
class FedenaEmailer < ActionMailer::Base
def emails(sender,recipients, subject, message,hostname,footer,rtl,other_details)
begin
recipient_emails = (recipients.class == String) ? recipients.gsub(' ','').split(',').compact : recipients.compact
setup_emails(sender, recipient_emails, subject, message,ho... |
class TextRenderer < Renderer
def render_header(text, level)
"\n #{'.'*level} #{text} \n"
end
def render_list(title, list, level = 4)
result = render_header(title, level)
list.each do |element|
result += "* #{element} \n"
end
result
end
end |
require 'rails_helper'
RSpec.describe CampaignsController, type: :controller do
let(:campaign) { create(:valid_campaign) }
describe 'GET #index' do
it 'renders index template' do
get :index
is_expected.to render_template(:index)
end
end
describe 'GET #show' do
it 'renders show templat... |
# Problem 124: Ordered radicals
# http://projecteuler.net/problem=124
#
# The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 2^3× 3^2× 7, so rad(504) = 2 × 3 × 7 = 42.
# If we calculate rad(n) for 1 ≤n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are ... |
class Recipe
attr_accessor :name,:duration,:ingredients,:produces,:category,:production_rate
# Constructor from string describing a recipe using format
# <name>@<category>@<duration>@<quantity1>:<product1>,<quantity2>:<product2>...@<quantity1>:<ingredient1>,<quantity2>:<ingredient2>...
def initialize(s)
... |
class ArticlePolicy < ApplicationPolicy
%w(new? create? edit? update? destroy?).each do |m|
define_method(m) do
admin?
end
end
def index?
true
end
def show?
record.published? || admin?
end
end
|
require File.join(File.dirname(__FILE__), *%w{.. spec_helper})
class Chef
describe ExpectException do
let(:m1){ 'message' }
let(:m2){ 'message2' }
let(:r){ 'return object' }
let(:block){ Proc.new{|mess, exp| r} }
let(:cm){ :chef_message }
let(:e){ ErrorStub.new(m1) }
let(:e2){ ErrorStub.n... |
require 'gilded_rose'
require 'item'
describe GildedRose do
describe '#update_quality for... ' do
describe 'Conjured items' do
it 'degrades quality of conjured items 2x speed but sell_in by 1' do
items = [Item.new('conjured mana cake', 10, 10)]
expect { GildedRose.new(items).update_quality }... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Shared::PropertyNameAliases do
describe '#abbreviated_alias_for' do
it 'finds the abbreviated alias for a long property name' do
expect(described_class.abbreviated_alia... |
module ApplicationHelper
def text_with_icon(icon_path, side, text)
("#{image_tag icon_path, size: convert_side(side)} " + text).html_safe
end
def convert_side(side)
"#{side}x#{side}"
end
end
|
# frozen_string_literal: true
require 'rspec/expectations'
RSpec::Matchers.define :match_ignoring_indents do |expected|
match do |actual|
normalize(actual) == normalize(expected)
end
failure_message do |actual|
%(
expected that
#{normalize(actual)}
would be equal to
#{normalize(... |
# require 'rspec/autorun'
# require 'algorithms'
# include Algorithms
# require 'active_support/all'
# The above statements are useful when running in
# coderpad.io/sandbox
require 'securerandom'
require 'set'
require 'active_support/all'
RSpec.describe 'BinarySearch testing iteration 1' do
it 'should search for a... |
class UsersController < ApplicationController
before_action :authenticate_user!, except: [:profile]
authorize_resource
def profile
@user = User.find(params[:id])
@num_posted = @user.poster_jobs.size
@num_offered = @user.bids.size
@num_helped = @user.helper_jobs.size
end
end
|
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
config.vm.box_check_update = false
config.vm.provision "shell", inline: <<-SHELL
apt-get update
apt-get install -y apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/lin... |
require "open3"
module LanguageServer
module Linter
class Error
attr_reader :line_num, :characters, :message, :type
def initialize(line_num:, characters: 0..0, message:, type:)
@line_num = line_num
@characters = characters
@message = message
@type = type
end
... |
require 'rails_helper'
RSpec.describe Api::V1::UsersController do
describe "GET #index" do
before do
get :index
end
it "returns http success" do
expect(response).to have_http_status(:success)
end
it "JSON body response contains expected user attributes" do
json_response = JSON.p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.