text stringlengths 10 2.61M |
|---|
require './game'
describe Game do
let(:game) { Game.new }
# perfect game
it 'can roll all strikes' do
12.times { game.roll(10) }
expect(game.scorecard).to eq 300
end
# guttter game
it 'can roll all 0s ' do
20.times { game.roll(0) }
expect(game.scorecard).to eq 0
end
# spares game
i... |
class Category
attr_accessor :name, :min, :max, :avg, :ranking
def initialize(name)
@name = name
@min = 100000
@max = 0
@avg = 0
@ranking = []
end
def to_s
"#{@name} (#{@min} to #{@max}, avg: #{@avg})"
end
end |
require 'rails_helper'
RSpec.describe Doctor, type: :model do
context 'associations' do
it { should have_and_belong_to_many(:teams) }
it { should have_many(:patients) }
end
end
|
class Image < ApplicationRecord
has_many :images_users
has_many :users, through: :images_users
validates :url, format: {
with: /https?:\/\/(www\.)?\w+\.\w{2,}(\/\w*)*/,
}
end
|
require 'test_helper'
class ChefsEditTest < ActionDispatch::IntegrationTest
def setup
@chef = Chef.create!(chefname: "mashrur", email: "vincent@example.com",
password: "password", password_confirmation: "password")
@chef2 = Chef.create!(chefname: "vincent2", email: "vincent2@examp... |
require 'spec_helper'
describe RegistrationsController do
before(:each) do
@u1 = create(:user,
:password => '11111111', :password_confirmation => '11111111'
)
@u2 = create(:user)
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in(@u1)
end
context "when editing own account" ... |
class Song < ActiveRecord::Base
include PublicActivity::Model
tracked owner: Proc.new{ |controller, model| controller.current_user }, only: :create
after_save :parse_notes
before_save :set_creator
has_many :notes
has_many :posts
has_many :user_song_preferences
belongs_to :origin_church, :class_name =... |
def app_path
ENV['APP_BUNDLE_PATH'] || (defined?(APP_BUNDLE_PATH) && APP_BUNDLE_PATH)
end
def fill_in_on_screen(field, text: null)
text_field_selector = "view marked:'#{field}'"
check_element_exists(text_field_selector)
frankly_map(text_field_selector, 'becomeFirstResponder')
frankly_map(text_field_sele... |
require 'test_helper'
class AppTest < ActiveSupport::TestCase
setup do
@app = apps(:one)
end
test_fixtures
test_dependent_associations(destroy: Token)
test 'name should be present' do
@app.name = ' '
assert_not @app.valid?
end
test 'name should not be too long' do
@app.name = 'a' * 256... |
# frozen_string_literal: true
class UserMessagesController < ApplicationController
before_action :authenticate_user
before_action :set_user_message, only: %i[show edit update destroy]
before_action do |_request|
access_denied if @user_message && !admin? && @user_message.user_id != current_user.id
end
de... |
class LiveCell
def self.lives?(live_neighbours)
if(live_neighbours > 3)
false
elsif(live_neighbours == 1)
false
else
true
end
end
end
describe "A live cell" do
it "dies when it has more than 3 live neighbours" do
LiveCell.lives?(4).should == false
end
it "dies... |
require 'minitest/autorun'
require 'minitest/pride'
require './lib/turn'
require './lib/sequence'
require './lib/round'
require 'pry'
class RoundTest < Minitest::Test
def setup
@beginner_round = Round.new('b')
@intermediate_round = Round.new('i')
@advanced_round = Round.new('a')
end
def test_it_exis... |
class TasksController < ApplicationController
def create
@task = Task.new(params[:task])
@task.save
flash[:notice] = t(:task_created)
redirect_to params[:return_url]
end
def update
@task = Task.find params[:id]
unless @task.complete?
@task.complete!
else
@task.incomplet... |
class SlackApi
USER_NAME = 'Slack Voter'
POST_PARAMS = { username: USER_NAME }
def initialize(url)
@url = url
end
def post_message(action, *args)
json = send(action, *args)
RestClient.post @url, json, content_type: :json, accept: :json
end
def new_survey(survey)
POST_PARAMS.merge({
... |
class ModelMailer < ActionMailer::Base
default from: "Leboncoin@ensiie.fr"
# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.model_mailer.signal_annonce.subject
#
def signal_annonce(admin)
@admins = admin
@greeting = "Hi"
mail to: @admins[0... |
class Championship < ApplicationRecord
class InvalidParticipantsNumber < StandardError; end;
class InvalidChampionshipType < StandardError; end;
belongs_to :championship_type
belongs_to :user
has_many :participants
has_many :users, through: :participants
has_many :pontoscorridos_partidas
has_many :bra... |
class AddcolomMorimoris < ActiveRecord::Migration[5.0]
def change
add_column :morimoris, :mainsub_id, :integer
add_column :morimoris, :mainsub_name, :string
end
end
|
module Kafkat
module Command
class CleanIndexes < Base
register_as 'clean-indexes'
usage 'clean-indexes',
'Delete untruncated Kafka log indexes from the filesystem.'
def run
print "This operation will remove any untruncated index files.\n"
begin
print "\n... |
require 'collins/state/mixin'
require 'escape'
module Collins
# Provides state management via collins tags
class PersistentState
include ::Collins::State::Mixin
include ::Collins::Util
attr_reader :collins_client, :path, :exec_type, :logger
def initialize collins_client, options = {}
@col... |
require 'osc'
class LightRemote::Light
attr_accessor :host, :port, :osc
def initialize(host, options={})
options = { :port => 2222 }.merge(options)
@host = host
@port = options[:port]
@osc = OSC::UDPSocket.new
end
# Sends RGB value in range [0, 1] to light.
def send_light(r, g, b)
#put... |
class PlaceReservationsController < ApplicationController
before_action :set_place_reservation, only: [:destroy]
def index
#@place_reservations = current_user.place_reservations.paginate(page: params[:page], per_page: 8)
@place_reservations = PlaceReservation.joins(:user, :place).where("cast(users.id as text) ... |
describe Sulfuras do
let(:sulfuras) {Sulfuras.new(Item.new("Sulfuras, Hand of Ragnaros", 0, 80))}
it 'inherits from Item' do
expect(Sulfuras).to be < Item
end
it 'initializes with a name, sell_in, and quality' do
expect(sulfuras.name).to eq("Sulfuras, Hand of Ragnaros")
expect(sulfuras.sell_in).to... |
class TicketController < ApplicationController
def index
@departments = []
Department.all.each do |dep|
@departments << [dep.title, dep.id]
end
end
def create_ticket_post
wait_for_staff_status = TicketStatus.where(title: 'Waiting for Staff Response').first.try(:id)
if params[:department... |
module Riskified
class Configuration
attr_accessor :sandbox_mode, :sync_mode, :auth_token, :default_referrer, :shop_domain
def initialize
@sync_mode = true # pre-configured by default, since the async mode is not supported.
@sandbox_mode = nil
@auth_token = nil
@default_referrer = nil... |
require 'test/unit'
require 'yaml'
class Load_tests < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
def test_load_from_string
foo = YAML::load('answer: 42')
assert(foo.size == 1)
assert(foo['answer'] == 42)
end
def test_repetitive_loads
test_load_from_string... |
require "test_helper"
require 'date'
describe VideosController do
describe "index" do
it "must get index" do
# Act
get videos_path
body = JSON.parse(response.body)
# Assert
expect(body).must_be_instance_of Array
expect(body.length).must_equal Video.count
# Check that e... |
class EmployerDemographicsImportProcess
include Sidekiq::Worker
sidekiq_options queue: :employer_demographics_import_process, retry: 1
def perform(file_path)
require 'open-uri'
file = open(file_path, encoding: 'utf-16')
headers = file&.first&.split("\t").map(&:parameterize).map(&:underscore).map... |
require 'sinatra'
require 'sinatra/activerecord'
require './models'
require 'bundler/setup'
require 'sinatra/flash'
set :database, 'sqlite3:winter.sqlite3'
set :sessions, true
def current_user
if session[:user_id]
User.find(session[:user_id])
end
end
get "/" do
@user = User.new
erb :home
end
get "/user" ... |
module ApplicationHelper
# Return a transformed text in HTML through markdown
def markdown(text)
renderer = Redcarpet::Render::HTML.new(render_options = {
:prettify => true
})
markdown = Redcarpet::Markdown.new(render... |
class AddCoverToEmpresa < ActiveRecord::Migration[5.0]
def change
add_attachment :empresas,:cover
end
end
|
class FantasyTeamsController < ApplicationController
before_action :authenticate_user!
before_action :set_fantasy_team, only: [:show, :edit, :update, :destroy]
before_action :set_fantasy_league
def index
@fantasy_teams = FantasyTeam.all
end
def new
@fantasy_team = @fantasy_league.fantasy_teams.... |
require 'test_helper'
class ResponseMailerTest < ActionMailer::TestCase
def setup
@writer = create(:writer)
@submission = create(:submission, writer: @writer)
@desc = create(:description, submission: @submission)
@response = create(:response, description: @desc)
end
test "response_notification"... |
FactoryGirl.define do
factory :deal_confirmation, class: IGMarkets::DealConfirmation do
affected_deals []
deal_id 'id'
deal_reference 'reference'
deal_status 'ACCEPTED'
direction 'BUY'
epic 'CS.D.EURUSD.CFD.IP'
expiry '20-DEC-40'
guaranteed_stop false
level 100.0
limit_distance... |
class RemoveTimeFromLogin < ActiveRecord::Migration
def up
remove_column :logins, :time
end
def down
add_column :logins, :time, :datetime
end
end
|
require './board'
RSpec.describe Board do
describe "#positions" do
it "return total board positions" do
board = Board.new(3,4)
board.totalPositions
expect(board.totalPositions).to eq 12
end
end
end
|
require_relative 'test_helper'
require_relative '../lib/cpu_player'
require_relative '../lib/player'
require_relative '../lib/ship'
class PlayerTest < MiniTest::Test
def setup
@cpu = CpuPlayer.new("1")
@player = Player.new("1")
@c_cruiser = Ship.new("Cruiser", 3)
@c_submarine = Ship.new("Submarine", ... |
class ConvertWikiNotesToHtml < ActiveRecord::Migration
def self.up
say_with_time "Converting Wiki pages to HTML" do
WikiRevision.find(:all).each do |rev|
rev.body = RedCloth.new(rev.body).to_html(:block_textile_table, :block_textile_lists, :block_textile_prefix, :inline_textile_image, :inline_texti... |
class Game < ActiveRecord::Base
has_many :players
def self.authenticate(id, password)
game = Game.find(id)
if game.blank? || password != game.password
return nil
else
return game
end
end
def other_player(this_player)
(self.players - [this_player]).first
end
end
# == Sche... |
require 'spec_helper'
describe SqlResultPresenter, :type => :view do
let(:schema) { gpdb_schemas(:default) }
let(:result) do
SqlResult.new.tap do |result|
result.add_column("size", "real")
result.add_column("is_cool", "boolean")
result.add_row(["11", "t"])
result.add_row(["21", "f"])
... |
class Video < ActiveRecord::Base
paginates_per 50
belongs_to :video_category
belongs_to :image
def image_link
image = self.image
image && image.filename ? ActionController::Base.helpers.asset_path(image.filename) : ActionController::Base.helpers.asset_path("placeholders/videogame-placeholder.png")
end
end
|
class AddDaysPlayedToPlayerIds < ActiveRecord::Migration
def change
add_column :player_ids, :days_played, :string
end
end
|
require 'tmpdir'
require 'minitest/autorun'
require 'minitest/spec'
require 'apt_control'
require 'inifile'
module CLIHelper
def self.included(other_mod)
other_mod.instance_eval do
after do
FileUtils.rm_r(@working_dir) if File.directory?(@working_dir)
end
let :build_archive_dir do
... |
module TmuxStatus
module Wrappers
class AcpiBattery
def percentage
return 100 if charged?
output.scan(/(\d{1,3})%/).flatten.first.to_i
end
def charged?
output.include? 'Full'
end
def charging?
output.include? 'Charging'
end
def dischar... |
# coding: utf-8
class Word
attr_accessor :id, :position, :form, :lexeme_id, :inflection, :tags, :greek_note, :english_note
def initialize(id, position, form, lexeme_id, inflection, tags)
@id = id
@position = position
@form = form
@lexeme_id = lexeme_id
@inflection = inflection
@tags = tags... |
class Api::V1::UsersController < ApplicationController
respond_to :json
skip_before_action :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
before_action :authenticate_request!
def create
user = User.new(user_params)
if user.save
render :json... |
# frozen_string_literal: true
class SettingsController < ApplicationController
def signin
return unless params["settingType"] == "account"
store_location_for(:user, "account_details")
end
def signup; end
def signout; end
def mln_banner_message
unless ENV.fetch('SHOW_MAINTENANCE_BANNER'... |
require 'open-uri'
require 'json'
class GamesController < ApplicationController
def new
@letters = ('a'..'z').to_a.sample(10)
end
def score
@letters = params[:letters].split('')
@answer = params[:answer].upcase
@score = @answer.length
@exist = exist?(@letters, @answer)
@english = english... |
module FlexUtils
class Adl < AbstractTool
attr_writer :swf,
:title,
:visible,
:transparent,
:width,
:height,
:x,
:y,
:system_chrome,
:arguments,
:descri... |
class CreateChapters < ActiveRecord::Migration[5.0]
def change
create_table :chapters do |t|
t.time :duracion
t.text :resumen
t.integer :numero
t.integer :temporada
t.string :nombre
t.timestamps
end
end
end
|
require "webstop-api/rest/consumer_sessions"
require "webstop-api/models/consumer"
module WebstopApi
module Interfaces
module ConsumerSessions
include WebstopApi::REST::ConsumerSessions
def login(credentials)
response = _login(credentials.merge(retailer_id: WebstopApi.retailer_id))
... |
class User < ApplicationRecord
devise :two_factor_authenticatable, :rememberable, :secure_validatable, :recoverable,
otp_secret_encryption_key: ENV["SECRET_KEY_BASE"]
belongs_to :organisation
has_many :historical_events
validates_presence_of :name, :email
validates :email, with: :email_cannot_be_changed_... |
%w( rubygems rack/test ).each {|lib| require lib }
require File.dirname(__FILE__) + '/../examples/sinatra-app'
describe 'Example Sinatra app' do
include Rack::Test::Methods
def app
Sinatra::Application
end
before do
# because we keep resetting Page.dir in the specs,
# we need to point it to the... |
require 'rails_helper'
describe Api::V1::FormulationsController do
before do
@formulation = FactoryBot.create(:formulation)
end
describe '#index' do
it 'successfully renders list of Formulations with Ingredients' do
get :index, params: {format: :json}
expect(response).to have_ht... |
require 'spec_helper'
describe Boxzooka::Endpoint do
let(:endpoint) { boxzooka_endpoint }
let(:response) { endpoint.execute(request) }
end
|
desc "Enviar correos de mantenimientos pendientes."
task enviar_pendientes: :environment do
users = User.distinct.joins(owner: {cars: :maintenance_histories}).where("maintenance_histories.status = 'Pendiente'")
users.each do |user|
UserNotifierMailer.send_pending_reviews(user).deliver
end
end
desc "R... |
class MessagesController < ApplicationController
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.save
flash[:notice] = 'Mensagem criada com sucesso'
ContactMailer.new(@message.id).deliver
else
flash[:alert] = 'Por favor, preencha... |
class AddEndingTimeToProposals < ActiveRecord::Migration
def change
add_column :proposals, :end_time, :datetime
end
end
|
class ApplicationController < ActionController::Base
def forem_user
current_user
end
helper_method :forem_user
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, i... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :blogs
# 基本の7つのルーティングを定義するため
# ここに記載はされないが、GET blogs#new 等は設定されている
# 確認したい場合は $ rake routes
# また、_pathのURL用ヘルパー?も自動で追加されている
end
|
RESULT_FILE = 'results.txt'.freeze
LOG_FILE = 'general.log'
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
def handle_exception(method_name, exception)
log_event method_name, exception.message
log_event method_name, exception.backtrace.inspect
puts exception.message
end
def log_event(method_name, message)
# YYYY-MM-DD HH:... |
require 'spec_helper'
describe EssayDetail::AuthorBiography do
let(:essay) { double(Essay, author: 'author', author_biography: double(MarkdownContent, content: 'biography'), author_image: double(Image, url: 'url')) }
subject { described_class.new(essay) }
describe 'self_render' do
it "instanciates itself... |
module Airplay
class Player
class Media
attr_reader :url
def initialize(file_or_url)
@url = case true
when File.exists?(file_or_url)
Airplay.server.serve(File.expand_path(file_or_url))
when !!(file_or_url =~ URI::regexp)
file_or_... |
require 'rake'
require 'rspec/core/rake_task'
namespace :new_recipe do
desc 'add new folder and default.rb'
task :create, ['name'] do |tasks,args|
name = args[:name]
command = ''
command << "mkdir ./cookbooks/#{name} &&"
command << "touch ./cookbooks/#{name}/default.rb"
sh command
end
end
namespace :a... |
class Account < ApplicationRecord
has_many :movements
belongs_to :user
end |
require 'spec_helper'
describe Metasploit::Model::Search::Operator::Group::Union do
it { should be_a Metasploit::Model::Search::Operator::Group::Base }
context 'operation_class_name' do
subject(:operation_class_name) {
described_class.operation_class_name
}
it { should == 'Metasploit::Model::Se... |
require 'rails_helper'
RSpec.describe GamesController, :type => :controller do
describe "GET index" do
fixtures :games
it "returns http success" do
get :index
expect(response).to have_http_status(:success)
end
it "creates a new game when index page is loaded" do
#change matcher exp... |
Given /^(provider "[^"]*") requires cinstances to be approved before use$/ do |provider|
provider.application_plans.each do |plan|
plan.approval_required = true
plan.save!
end
end
Then /^(buyer "[^"]*") should have (\d+) cinstances?$/ do |buyer_account, number|
assert_equal number.to_i, buyer_account.bo... |
class UsersCourseRating < ApplicationRecord
belongs_to :user
belongs_to :course_rating
end
|
# frozen_string_literal: true
RSpec.describe ChatRoom, type: :model do
context 'Model Associations' do
it { is_expected.to belong_to(:user) }
it { is_expected.to have_many(:messages) }
end
end
|
class RenameColumnType < ActiveRecord::Migration
def up
rename_column :projects, :type, :project_type
end
def down
end
end
|
MRuby::Gem::Specification.new('mruby-sample') do |spec|
spec.license = 'MIT'
spec.authors = 'Yohei Kawahara'
spec.add_test_dependency 'mruby-httprequest'
spec.add_test_dependency 'mruby-json'
end
|
class Service < ActiveRecord::Base
belongs_to :user
has_many :orders
has_many :reviews
has_attached_file :image, { styles: { medium: "300x300",
small: "230x140",
thumb: "100x100" },
preserve_files: tru... |
require 'rails_helper'
describe Message, :vcr => true do
it "will create a message" do
visit new_message_path
fill_in :To, :with => '9876543210'
fill_in :From, :with => '0123456789'
fill_in :Body, :with => 'TESTING IN PROGRESS'
click_on "Create Message"
expect(page).to have_content('Your me... |
# lib/robot.rb
class Robot
attr_reader :placement, :placed
def initialize(table)
@table = table
@placed = false
end
def place(placement)
set_placement(placement)
end
def move
if @placed
position = @placement.position
orientation = @placement.orientation
case orientation... |
class AttachmentsController < ApplicationController
before_action :require_medusa_user
before_action :find_attachment_and_attachable, only: [:destroy, :show, :edit, :update, :download]
def destroy
authorize! :destroy_attachment, @attachable
@attachment.destroy
redirect_to @attachable
end
def sh... |
create_table "deploys", unsigned: true, force: :cascade do |t|
t.integer :application_id, null: false
t.integer :revision_id, null: false
t.boolean :current, default: false
t.timestamps
end
|
module Fog
module Compute
class Google
class Mock
def get_zone_operation(_zone_name, _operation)
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
class Real
# Get the updated status of a zone operation
# @see https:/... |
# frozen_string_literal: true
require 'csv'
require 'json'
require_relative 'models/all'
def lambda_handler(event:, context:) # rubocop:disable Lint/UnusedMethodArgument
output = CSV.generate do |csv|
csv << Product::FB_HEADERS
Product.with_type.each do |product|
csv << Product::FB_HEADERS.map do |hea... |
require "test_helper"
require "integration_test_case"
module ActionClient
class ClientTestCase < ActionClient::IntegrationTestCase
Article = Struct.new(:id, :title)
class BaseClient < ActionClient::Base
default url: "https://example.com"
end
setup do
BaseClient.defaults.headers = {}
... |
require_relative 'repository'
require 'time'
class MerchantRepository
include Repository
def initialize(merchants)
@list = merchants
end
def find_all_by_name(name)
@list.find_all do |merchant|
merchant.name.downcase.include?(name)
end
end
def create(attributes)
highest_merchant_id ... |
class App < ActiveRecord::Base
attr_accessible :name, :url, :description, :location, :logo,
:enabled, :app_pictures_attributes
validates_presence_of :name, :url, :description, :location, :logo
has_many :app_pictures
accepts_nested_attributes_for :app_pictures, allow_destroy: true
scope :a... |
# Calculate the mode Pairing Challenge
# I worked on this challenge [by myself, with: ]
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented.
# 0. Pseudocode
# What is the inp... |
class AddReferencesToStoreAuth < ActiveRecord::Migration[6.1]
def change
add_reference :stores, :store_auth, foreign_key: true
end
end
|
class CreateComplaints < ActiveRecord::Migration
def change
create_table :complaints do |t|
t.string :title
t.text :desc
t.integer :status, default: 0
t.integer :random, default: 0
t.boolean :view_publically, default: false
t.integer :user_id, null: false
t.timestamps nu... |
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://rubydoc.brew.sh/Formula
class Tser < Formula
desc "A TypeScript virtual machine."
homepage "https://github.com/tser-project/tser"
version "0.0.2"
url "https://github.com/tser-project/tser/releases/download/v#{version}/mac64_#{versio... |
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :deal_site_category
t.string :major_category
t.string :sg_category
t.text :description
t.string :photo
t.timestamps
end
end
end
|
FactoryBot.define do
factory :list do
description { Faker::Lorem.sentence }
is_private { false }
sublist_max_level { 0 }
user
trait :has_parent do
user { nil }
parent_list { association :list }
end
factory :sublist, traits: %i[has_parent]
end
end
|
ActiveAdmin.register Purchase do
controller do
def permitted_params
params.permit!
end
end
form do |f|
f.inputs do
input :email
input :price
input :purchasable_id
input :status
input :start_date
input :contact
input :phone_number
input :pickup
... |
class Team < ApplicationRecord
belongs_to :tournament
validates :name, presence: true, uniqueness: { scope: :tournament_id }
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
helper :all
layout "application"
rescue_from Exception, :with => :my_log_error
rescue_from ActiveRecord::RecordNotFound, :with => :my_log_error
rescue_from ActionController::UnknownController, :with => :my_log_error
rescue_from Ac... |
# frozen_string_literal: true
require 'rspec/sleeping_king_studios/concerns/shared_example_group'
require 'stannum/rspec/match_errors'
require 'support/examples'
module Spec::Support::Examples
module ConstraintExamples
extend RSpec::SleepingKingStudios::Concerns::SharedExampleGroup
include Stannum::RSpec:... |
require 'test_helper'
class TranslatableTest < ActiveSupport::TestCase
test 'not update phraseapp translation if force flag is not set' do
orga = build(:orga)
orga.expects(:update_or_create_translations).never
orga.save
end
test 'not upload translation if no attributes are changed' do
orga = ... |
require 'legacy_migration_spec_helper'
require 'base64'
TYPE_MAP = {
"image/png" => "PNG",
"image/jpeg" => "JPEG",
"image/gif" => "GIF"
}
describe ImageMigrator do
describe ".migrate" do
before :all do
ImageMigrator.migrate
end
describe "copying the data" do
it "gives an image attachm... |
class LocationSerializer < ActiveModel::Serializer
attributes :name, :external_id
end
|
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a probl... |
# add class for each move
class Move
VALUES = ['rock', 'paper', 'scissors', 'lizard', 'spock'].freeze
def initialize(value)
@value = value
end
def to_s
@value
end
end
class Rock < Move
def >(other_move)
other_move == 'scissors' || other_move == 'lizard'
end
def <(other_move)
other_... |
class WorksheetProblem < ActiveRecord::Base
belongs_to :worksheet
belongs_to :math_problem
has_one :problem_level, :through => :math_problem
accepts_nested_attributes_for :math_problem
validates_uniqueness_of :problem_number, :scope => :worksheet_id
validate :worksheet_exists, :math_problem_exists
... |
class MoviesController < ApplicationController
def index
@movie = Movie.new
end
def search
@search_word = params[:movie][:title]
@movies = Movie.where("title LIKE ?", "%#{@search_word}%")
if @movies.count > 0
render "search"
else
results = Imdb::Search.new(@search_word)
@mov... |
class CreateMountains < ActiveRecord::Migration[6.0]
def change
create_table :mountains do |t|
t.text :name
t.integer :height_metres
t.text :country
t.integer :first_ascent
t.timestamps
end
end
end
|
# Exercise 19: Functions and Variables
# https://learnrubythehardway.org/book/ex19.html
# Creates a function with two parameters: cheese_count which is an integer that is the amount of cheese and boxes of cracker which is how many crackers we'll need. The function prints those values into a few strings
def cheese_and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.