text stringlengths 10 2.61M |
|---|
class Category < ActiveRecord::Base
has_attached_file :photo
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/
has_many :labels
has_many :items, through: :labels
def photo_url
photo.url
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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# ... |
require "application_system_test_case"
class QueriesTest < ApplicationSystemTestCase
setup do
@query = queries(:one)
end
test "visiting the index" do
visit queries_url
assert_selector "h1", text: "Queries"
end
test "creating a Query" do
visit queries_url
click_on "New Query"
click_... |
class CreateInstantFees < ActiveRecord::Migration
def self.up
create_table :instant_fees do |t|
t.integer :instant_fee_category_id
t.string :custom_category
t.integer :payee_id
t.string :payee_type
t.string :guest_payee
t.decimal :amount, :precision => 15, :scale => 2
t.d... |
class Review < ApplicationRecord
belongs_to :product
validates :rating, presence: true
validates :rating, numericality: { only_integer: true }
validates :rating, numericality: { greater_than_or_equal_to: 1 }
validates :rating, numericality: { less_than_or_equal_to: 5 }
validates :title, presence:... |
class CreateProcessedSubmissions < ActiveRecord::Migration[6.0]
def up
create_table :processed_submissions, &:timestamps
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
MissingUserAgentError = Class.new(StandardError)
MissingAuthorizationError = Class.new(StandardError)
InvalidAuthorizationError = Class.new(StandardError)
rescue_from MissingUserAgentError, with: :unauthorized_... |
class Class
def attr_accessor_with_history attr_name
@attr_name = attr_name.to_s # make sure it's a string
attr_reader @attr_name # create the attribute's getter
attr_reader @attr_name+"_history" # create bar_history getter
@definition = %Q{
def initialize
@history_hash = Hash.n... |
module Spree::Chimpy
module Interface
class Carts < Orders
delegate :log, :store_api_call, to: Spree::Chimpy
def initialize
@upserter_class = CartUpserter
@create_method = :carts
end
end
end
end
|
require "application_system_test_case"
class BackendDashboardTest < ApplicationSystemTestCase
test "User index not allowed if user is not logged in" do
visit backend_dashboard_path
assert has_text?("Please, log in before continuing.")
assert_equal "/users/sign_in", current_path
end
test "User inde... |
class Staff < ActiveRecord::Base
#has_many :contacts, as: :contactable, inverse_of: :contacts, dependent: :destroy
has_many :contacts, as: :contactable, inverse_of: :contactable, dependent: :destroy
accepts_nested_attributes_for :contacts
validates_presence_of :name, :title1, :role
validates :role, inclusion... |
class Source < ActiveRecord::Base
validates_presence_of :identifier,
:root_url
validates_uniqueness_of :identifier,
:root_url
has_many :payloads #, :campaigns <--why won't this work? TODO
def urls
payloads.group("url")
.count
.sort_b... |
# require 'prime'
#
# def prime?(n)
# if n.prime?
# return true
# else
# return false
# end
# end
def prime?(n)
#Yet another way to say the same thing is that a number n is prime if it is greater than one and if none of the numbers divides n evenly
if n <= 0 || n == 1
return false
else
(2..... |
class Bus
attr_reader :route, :destination
def initialize(route, destination, passengers)
@route = route
@destination = destination
@passengers = passengers
end
def drive
return "Brum Brum"
end
def number_of_passengers
return @passengers.length
end
def pickup_passenger(person)
... |
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
#ruby 数组 学习
=begin
Ruby 数组是任何对象的有序整数索引集合。数组中的每个元素都与一个索引相关,并可通过索引进行获取。
数组的索引从 0 开始,这与 C 或 Java 中一样。一个负数的索相对于数组的末尾计数的,也就是说,索引为 -1 表示数组的最后一个元素,-2 表示数组中的倒数第二个元素,依此类推。
Ruby 数组可存储诸如 String、 Integer、 Fixnum、 Hash、 Symbol 等对象,甚至可以是其他 Array 对象。
Ruby 数组不需要指定大小,当向数组添加元素时,Ruby 数组会自动增长。
=... |
# This module holds a set of helper functions used by scripts and specs
# to manage various parts of constructing the TIPR package
require 'erb' # ERB for generating our xml files
require 'digest/sha1' # SHA1 library for calculating checksums
require 'libxml' # For validating our xml files against sche... |
require 'spec_helper'
describe User do
subject { User.make }
before(:all) do
User.delete_all
subject.feeds = (0..4).map do |num|
Feed.new(name: "Some Feed #{num}", default: true)
end
end
after(:all) { User.delete_all }
describe 'Persistence' do
it { should be_valid }
it { sho... |
#!/usr/bin/env ruby
require "biocyc"
require "openflux"
require "thor"
module OpenFLUX # :nodoc:
module BioCyc # :nodoc:
class Equation < OpenFLUX::Equation # :nodoc:
# Construct an instance using a BioCyc Reaction
#
# @param biocyc_reaction [BioCyc::Reaction]
# @return [OpenFLUX::BioCyc... |
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rpgview/version'
Gem::Specification.new do |gem|
gem.name = "rpgview"
gem.version = Rpgview::VERSION
gem.authors = ["Nick Maloney"]
gem.email = ["ng... |
class FreeItemRequestsController < ApplicationController
before_action :set_free_item, only: %i[give_away new]
before_action :set_request, only: :give_away
def new
@request = FreeItemRequest.create(item: @item, actual_owner: @item.user, potential_owner: current_user)
redirect_to root_path, notice: "You'v... |
module MotionBuild
class Rule
attr_reader :dependencies, :project
attr_writer :forced
def initialize(project)
@project = project
@dependencies = []
@forced = false
end
# The *active* rule requires its *action* to be performed this build cycle
def active?
false
end... |
module AnonymousUser
extend ActiveSupport::Concern
included do
scope :anonymous, -> (id = nil, &block) do
User.new id: id.nil? ? (-Time.now.to_i + rand(10000)) : id do |u|
u.created_at = Time.now
u.updated_at = Time.now
u.username = "游客#{u.id.abs}"
self.instance_eval {
... |
# frozen_string_literal: true
describe MovieExportMailer, type: :mailer do
describe "#send_file" do
subject(:send_file) { described_class.send_file(user.id, file_path) }
let(:file_path) { "tmp/movies.csv" }
let(:user) { create(:user) }
let(:csv) { "such;a;cool;csv\ndont;you;think;so\n" }
before... |
#!/usr/bin/env ruby
#require 'caltime'
require 'caltime'
require 'highline/import'
require 'optparse'
options = {}
OptionParser.new do |opt|
opt.on('--credentials FILENAME') { |o| options[:credentials] = o }
opt.on('--punch') { |o| options[:punch] = true }
opt.on('--quiet') { |o| options[:print] = true }
end.pa... |
class Guest
attr_reader :name
@@all = []
def initialize(name)
@name = name
@@all << self
end
def self.all
@@all
end
def trips
Trip.all.select { |trip| trip.guest == self }
# - returns an array of all trips a guest has made
end
def listings
trips.collect { |trip| trip.listing}.uniq
... |
module ApplicationHelper
def title(page_title)
content_for :title, page_title.to_s
end
def meta_tag(tag, text)
content_for :"meta_#{tag}", text
end
def yield_meta_tag(tag, default_text='')
content_for?(:"meta_#{tag}") ? content_for(:"meta_#{tag}") : default_text
end
def hashtags_html_conve... |
require 'bcrypt'
describe User do
before(:each) do
clean_test_database
User.add(email: "mark@yahoo.com",
phone_num: "1234",
password: "abcd")
end
it "find user details" do
user = User.find(email: "mark@yahoo.com")
expect(user.first.email).to eq("mark@yahoo.com")
end
it 'authenti... |
require 'spec_helper'
describe "beers/new" do
before(:each) do
assign(:beer, stub_model(Beer,
:title => "MyString",
:content => "MyText"
).as_new_record)
end
it "renders new beer form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
... |
require 'rails_helper'
require 'shoulda-matchers'
RSpec.describe RegUser, type: :model do
it { should validate_presence_of(:email) }
# it { should validate_uniqueness_of(:email) }
# it { should validate_presence_of(:encrypted_password) }
it { should validate_presence_of(:first_name) }
it { should validate_pr... |
choice = 0
loop do
puts ">> How many output lines do you want? Enter a number >= 3: "
choice = gets.chomp.to_i
break if choice >= 3
puts ">> That's not enough lines."
end
while choice > 0
puts "Launch School is the best!"
choice -= 1
end
|
require 'rails_helper'
feature 'Identity downloads a document from the documents page', js: true, enqueue: false do
scenario 'and sees the documents counter decrement and disappear' do
given_i_have_created_an_identity_based_report
when_i_download_the_report
then_i_should_see_the_documents_counter_decrem... |
require "test_helper"
class RodauthTest < ActionDispatch::IntegrationTest
test "create account" do
rodauth = Rodauth::Rails.rodauth
visit pages_index_path
assert page.has_text?('You are not logged in')
visit rodauth.create_account_path
fill_in('login', with: 'test@example.com')
fill_in('pas... |
module Bitfinex
module StatsClient
# Various statistics about the requested pair.
#
# @param symbol [string] Symbol of the pair you want info about. Default 'btcusd'
# @return [Array]
# @example:
# client.stats('btcusd')
def stats(symbol = "btcusd")
get("stats/#{symbol}").body
... |
maintainer "J.D. Hollis"
license "Apache 2.0"
description "Enables the rabbitmq-management plugin and dependencies"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version "0.0.3"
depends "rabbitmq"
|
require 'graphviz'
require 'facets/string/titlecase'
module ConceptQL
class AnnotateGrapher
def graph_it(statement, file_path, opts={})
raise "statement not annotated" unless statement.last[:annotation]
@counter = 0
output_type = opts.delete(:output_type) || File.extname(file_path).sub('.', ''... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'spots#index'
resources :spots
end
# root GET / spots#index
# spots GET /spots(.:format) spots#index
# POST /spots(... |
RSpec.describe Group, type: :model do
it { should have_many(:workflowgroups) }
it { should have_many(:workflows).through(:workflowgroups) }
it { should have_many(:stages) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:contact_method) }
it { should validate_presence_of(:contac... |
class UserCartsController < ApplicationController
skip_before_action :authorize, only: :create
def index
render json: UserCart.all
end
def create
user = UserCart.create!(obj_params)
render json: user, status: :created
end
private
def obj_params
params.... |
class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks, dependent: :destroy
has_many :discussions, dependent: :destroy
has_many :comments, through: :discussions
has_many :memberships, dependent: :destroy
#project.memberships
has_many :members, through: :memberships, source: :user
#pr... |
class Notification < ActiveRecord::Base
validates :sparc_id,
:kind,
:action,
:callback_url,
presence: true
validate :duplicate_not_present?, on: :create
after_create :create_or_update_object
def duplicate_not_present?
if action == "create" && Notification.... |
require 'test_helper'
class ProjectsControllerTest < ActionController::TestCase
setup :activate_authlogic
setup :make_company
test "should get index" do
get :index,
:person_id => @person.to_param,
:company_id => @company.to_param
assert_response :success
assert_not_nil assigns(:proje... |
require "spec_helper"
describe GameWatchesController do
describe "routing" do
it "routes to #index" do
get("/game_watches").should route_to("game_watches#index")
end
it "routes to #new" do
get("/game_watches/new").should route_to("game_watches#new")
end
it "routes to #show" do
... |
require 'bundler/setup'
require 'pi_piper'
class LED
def initialize(pin:)
@pin = PiPiper::Pin.new(pin: pin, direction: :out)
end
def on
@pin.on
end
def off
@pin.off
end
def flash
loop do
@pin.on
sleep 1
@pin.off
sleep 1
end
end
end
if $0 == __FILE__
led... |
ALPHABET = ("a".."z").to_a
def decipher(string)
result = string.chars.map do |letter|
if ALPHABET.include?(letter.downcase)
n = ALPHABET.find_index(letter.downcase)
if n < 13
ALPHABET[n + 13]
else
i = 26 - n
idx = 13 - i
ALPHABET[idx]
end
else
" ... |
require 'spec_helper'
module ScriptNotifier
module Services
class TestService
include Services::Base
end
end
end
describe ScriptNotifier::Services::Base do
def failure_script_data(attrs = {})
sample_failure_script_data.merge!(attrs)
end
def success_script_data(attrs = {})
sample_suc... |
class QueryController < ApplicationController
def list_all_players
player_list = Player.all.as_json
render json: strip_fields(player_list)
end
def player_summary
name = params[:name].gsub(/_/, ' ')
player = Player.find_by(name: name)
player_hash = player.as_json
# General stats
playe... |
require File.join(File.dirname(__FILE__),'..','..','spec_helper')
describe Restfulie::Client::HTTP do
context "HTTP Base" do
let(:restfulie) { Restfulie.at("http://localhost:4567/") }
before :each do
WebMock.reset!
end
it "should get and respond 200 code" do
stub_request(:get, /.*\/tes... |
class PigLatinizer
attr_accessor :text
VOWELS = %w(a e i o u A E I O U)
def to_pig_latin(text)
out = []
text.split(" ").each do |word|
out << self.piglatinize(word)
end
out.join(" ")
end
def piglatinize(word)
if VOWELS.include?(word[0])
word + "way"
else
split = ... |
# frozen_string_literal: true
require_relative '../lib/game'
RSpec.configure do |rspec|
rspec.shared_context_metadata_behavior = :apply_to_host_groups
end
describe Game do
shared_context :partially_filled do
before do
subject.make_move(1, 0)
subject.make_move(1, 1)
subject.make_move(2, 0)
... |
#! ruby -Ku
require "open-uri"
require "rubygems"
require "wsse"
require "json"
def read_credential
File.open("config/ironnews.id") { |file|
return [file.gets.chomp, file.gets.chomp]
}
end
def create_token(username, password)
return Wsse::UsernameToken.build(username, password).format
end
username, passwo... |
# -*- encoding : utf-8 -*-
# The model of the device resource.
#
# This code is part of the Stoffi Music Player Project.
# Visit our website at: stoffiplayer.com
#
# Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com)
# Copyright:: Copyright (c) 2013 Simplare
# License:: GNU General Public License (stoff... |
class RemoveOriginFromSmallPosts < ActiveRecord::Migration
def self.up
remove_column :small_posts, :origin
end
def self.down
add_column :small_posts, :origin, :string
end
end
|
require 'spec_helper'
describe 'Automation Task' do
=begin
Points to focus on:
create an optimal solution
it should be possible to run the solution in CI
it should bootstrap itself (install dependencies).
"Write an automated test in your language and framework of choice whi... |
class ChangeColumnOnDeployments < ActiveRecord::Migration
def up
remove_column :deployments, :product_id, :company_id
end
def down
add_column :deployments, :product_id, :company_id
end
end
|
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/activerecord'
set :database, "sqlite3:leprosorium.db"
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :name, presence: true, length: { minimum: 3 }
validates :content, presence: true, length: { mi... |
class CreateResourceRequests < ActiveRecord::Migration
def change
create_table :resource_requests do |t|
t.string :lab_head_full_name
t.boolean :cfg_member
t.text :shipping_address
t.string :telephone
t.text :comment
t.timestamps
end
end
end
|
class SessionsController < ApplicationController
def create
landlord = Landlord.find_by_email(params[:email])
if landlord && landlord.authenticate(params[:password])
session[:landlord_id] = landlord.id
redirect_to dashboard_path
else
redirect_to '/login'
end
end
def destroy
... |
class List < ApplicationRecord
belongs_to :user
validates :subject, presence: true
validates :content, presence: true
end
|
class TopicsController < ApplicationController
before_filter :authenticate_user!
before_filter :load_research_folder
# GET /topics
# GET /topics.json
def index
@topics = @folder.topics.search(params[:search]).order(:progress).paginate(:page => params[:page], :per_page => 10).find_all_by_version('latest')
@... |
Rails.application.routes.draw do
root to: 'users#index'
resources :users, only: [:index, :new, :create, :show, :edit, :update, :destroy]
end
|
require 'nokogiri'
require 'open-uri'
require_relative 'view'
require_relative 'recipe'
class Controller
def initialize(cookbook)
@cookbook = cookbook
@view = View.new
end
def list
recipes = @cookbook.all
@view.display_all(recipes)
end
def create
name = @view.ask_for_user_input('name')
... |
class Spot < ActiveRecord::Base
belongs_to :post
belongs_to :province
belongs_to :city
belongs_to :user,:counter_cache => true
belongs_to :spot_tag,:counter_cache => true
validates_presence_of :name,:message=>APP_CONFIG['error_presence_spot']
validates_uniqueness_of :name,:message=>APP_CONFIG['error_... |
require 'spec_helper'
describe Event do
describe 'model' do
subject { @event = Event.new }
it { should respond_to( :id) }
it { should respond_to( :startdate) }
it { should respond_to( :fertilePeriod) }
it { should respond_to( :owner) }
end
describe ' owner' do
let(:event) { Even... |
class TrackingsController < ApplicationController
before_action :authenticate_user!
def index
@track_week = Invoice.where(:c_date => 1.week.ago..Date.today+1).where(:emailable => true, :emailed => nil)
@emailed = Invoice.where(:c_date => 1.week.ago..Date.today+1).where(:emailable => true).where.not(:... |
require "gtk3"
load 'Etat.rb'
load 'Aide.rb'
load 'PileAction.rb'
# Le plateau de jeu
# @attr_reader [String] niveau le niveau de difficulté
# @attr_reader [Array<String>] damier_correct le damier réponse au jeu en cours
# @attr_reader [Aide] aide une aide sur le plateau
# @attr_reader [Fixnum] taille la taille du pla... |
class EventUser < ActiveRecord::Base
belongs_to :event
belongs_to :user
validates :user_id, presence: true, uniqueness: { scope: :event }
def is_a_sub?
self.sub_for.present?
end
def subbing_for
User.find_by(id: self.sub_for)
end
end
|
feature 'testing hit points' do
scenario "can display player 2's hit points" do
sign_in_and_play
expect(page).to have_content 'Ken HP = 100'
end
scenario "shows a hit on player 2" do
sign_in_and_play
click_button "Attack"
expect(page).to have_content 'Ryu vs Ken'
end
scenario "shows a de... |
class System < ActiveRecord::Base
belongs_to :category
has_many :reviews
validates_presence_of :name, :category
end
|
FactoryGirl.define do
factory :calculator do
eight_hundred 1
six_hundred 1
discount_code "MyString"
photo_package false
end
end
|
class Like < ApplicationRecord
validates :user_id, {presence: true}
validates :blog_id, {presence: true}
belongs_to :user
belongs_to :blog
end
|
require 'rubygems'
require 'watir-webdriver'
# this class is the main entry point of the web page workflow.
# this class is instantiated before each scenario, and can be accessed globally
# some function that are used very often can also be put here.
# So that, you do not need to create a page instance to invoke th... |
class AddColumnToManagementWorkflows < ActiveRecord::Migration[5.1]
def change
add_column :management_workflows, :other_itvendors, :string
add_column :management_workflows, :other_itskills, :string
end
end
|
class User < ActiveRecord::Base
has_secure_password
has_many :events, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :meetups, dependent: :destroy
has_many :joined_events, through: :meetups, source: :event
validates :first_name, :last_name, :location, :state, presence: true
validates :pas... |
# frozen_string_literal: true
require 'rails_helper'
describe SendAdminEmail do
let(:user) { FactoryBot.create(:user) }
let!(:admin) { FactoryBot.create(:admin) }
before do
user.update_attributes(admin: true)
end
it 'should send a new admin email when a new admin is added' do
SendAdminEmail.call(u... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
test "requires email address" do
@user = User.new
@user.password = "1234"
@user.password_confirmation = "1234"
assert_not @user.save
end
test "requires password" do
@user = U... |
# frozen_string_literal: true
module Billing::Stripe::Webhooks::Customers::Subscriptions
class CreateOperation
def call(**params)
subscription = params.fetch(:subscription)
user = params.fetch(:user)
plan = subscription.plans.first
if subscription.trialing?
payment_dates = build... |
require "dry/validation"
module Tephue
module Entity
module Validatable
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def define_schema(&block)
@schema ||= Dry::Validation.Schema(&block)
end
def schema
@schema
... |
module MonthlyReports
module Collection
module Categories
class Stats
class Presenter
private
attr_reader :stats
public
def initialize(stats)
@stats = stats
end
def fetch_stat(stat_kind_path, category:)
stats[categ... |
class Category < ApplicationRecord
has_ancestry
has_many :categorizations
has_many :products, through: :categorizations
mount_uploader :picture, ProductPicturesUploader
def self.specialized_industries
Product.find_by_sql('select * from categories inner join specialized_industries ON special... |
class TweetsController < ApplicationController
# Find params before the following actions
before_action :set_tweet, only: [:edit, :update, :destroy]
# User needs to login before doing the following actions
before_action :authenticate_user!, only: [:new, :create, :edit, :destroy]
def new
@tweet = Tweet... |
describe Beheader::Constants do
let(:url_characters) { Beheader::Constants::URL_CHARACTERS }
context 'url characters' do
it 'contains lowercase literals' do
('a'..'z').each do |lowercase|
expect(url_characters).to include(lowercase)
end
end
it 'contains uppercase literals' do
... |
class AddDeviseToUsers < ActiveRecord::Migration
def self.up
change_table(:users) do |t|
t.string "encrypted_password", :default => "", :null => false
t.string "password_salt", :default => "", :null => false
## Recoverable
t.string :reset_password_token
... |
module SessionsHelper
def log_in(user)
session[:user_id] = user.id
end
def current_user
if session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
def authenticate_user
if session[:user_id] == nil
flash[:warning] = "会員情報を入力してくだい"
redirect_to login_path
... |
# frozen_string_literal: true
class ExchangeController < ApplicationController
RATE_EXPIRATION = 1.day
MAXIMUM_AMOUNT = 100_000_000
class InvalidCurrency < ArgumentError; end
class AmountTooHigh < ArgumentError; end
def rate
rates = fetch_currency_rates.body['rates']
currency_from = rates[params[:... |
require File.dirname(__FILE__) + '/../../../spec_helper'
describe 'Rackspace::Servers.delete_image' do
describe 'success' do
before(:each) do
# flavor 1 = 256, image 3 = gentoo 2008.0
@server_id = Rackspace[:servers].create_server(1, 3, 'name').body['server']['id']
@image_id = Rackspace[:serve... |
# frozen_string_literal: true
class CreateSlides < ActiveRecord::Migration[6.1]
def change
create_table :slides do |t|
t.belongs_to :playlist, null: false, foreign_key: true
t.belongs_to :content, null: false, foreign_key: true
t.bigint :weight, null: true, default: 0
t.timestamps
en... |
# frozen_string_literal: true
RSpec.describe JsonHashColumn do
let!(:coach) { create(:coach, social_links: {facebook: 'facebook.com'}) }
context 'social_links' do
it 'updates' do
coach.set(social_links: {facebook: 'new_facebook.com'})
expect(coach.social_links).to eq('facebook' => 'new_facebook.c... |
require 'rails_helper'
RSpec.describe FacilitiesManagement::ProcurementInvoiceContactDetail, type: :model do
let(:procurement_invoice_contact_detail) { create(:facilities_management_procurement_invoice_contact_detail) }
describe 'associations' do
it { is_expected.to belong_to(:procurement).class_name('Facilit... |
# In this exercise, you will write a method named xor that takes two arguments, and returns true if exactly one of its arguments is truthy, false otherwise.
def xor?(value1, value2)
value1 != value2
# return true if value1 && !value2
# return true if value2 && !value1
# return false
# return false if value1... |
# frozen_string_literal: true
RSpec.shared_examples_for "an applicative" do
describe ".pure" do
it "wraps a value with a context" do
expect(described_class.pure(1)).to eql(pure.(1))
end
it "wraps a block" do
fn = -> x { x + 1 }
expect(described_class.pure(&fn)).to eql(pure.(fn))
en... |
class AddCreditToImage < ActiveRecord::Migration
def change
add_column :headlines, :image_credit, :string
end
end
|
class Membership < ActiveRecord::Base
belongs_to :project
belongs_to :user
validates :user, uniqueness: {scope: :project, message: "has already been added"}
validates_presence_of :user
validates :role, presence: true
end
|
require "rails_helper"
RSpec.describe MediaController, type: :routing do
describe "routing" do
it "routes to #index" do
expect(:get => "/login").to route_to("sessions#index")
end
it "routes to #create" do
expect(:post => "/login").to route_to("sessions#create")
end
it "routes to #dest... |
# encoding: utf-8
Gem::Specification.new do |spec|
spec.name = 'free-image'
spec.version = '0.8.0'
spec.summary = 'Ruby Bindings for the Free Image Library'
spec.description = <<-EOS
FreeImage is an Open Source library project for developers who would like to support
popular graphics ima... |
require 'spec_helper'
module FizzBuzz
describe Generate do
let(:output) {double('output').as_null_object}
let(:fizzbuzz) {Generate.new(output)}
describe "#start" do
it "sends a welcome message" do
output.should_receive(:puts).with('This is FizzBuzz')
fizzbuzz.start
end
it "calls resp... |
class ContentsController < ApplicationController
before_action :set_campaign, except: [:your_posts]
before_action :authenticate_user!
before_action :set_content, only: [:show, :edit, :update, :destroy, :approve, :decline]
before_action :is_content_owner, only: [:edit, :update, :destroy]
before_action :is_camp... |
module Notification
def self.table_name_prefix
'notification_'
end
def self.notify(instance, action)
event = ::Notification::Event.new(instance, action)
# Get default handles
default_handles = ::Notification::Handles::Base.default
# Get receivers for event (User, Group, Status,... |
require 'minitest/autorun'
require_relative 'test_helper.rb'
describe FSM::Machine do
it 'initializes' do
parent = Object.new
machine = FSM::Machine.new(parent) { puts "do nothing" }
assert_equal parent, machine.parent
assert_equal Hash.new, machine.states
assert_nil ... |
FactoryGirl.define do
factory :credit_card do
name 'Taras Shevchenko'
number '1111111111111111'
expiration_date '12/96'
cvv '123'
trait :invalid do
name nil
number nil
end
end
end |
xml.instruct! :xml, :version => '1.0', :encoding => 'UTF-8'
xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do
xml.id "http://#{request.host_with_port}/"
xml.title "#{@settings.site_name}: Recent Posts"
xml.link :href => "http://#{request.host_with_port}/"
xml.updated @posts.first.created_at.iso8601
@post... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.