text stringlengths 10 2.61M |
|---|
class GigabitEthernetCondition
def initialize(params)
@params = params
end
def gigabit_ethernets
relation = GigabitEthernet.all
relation = relation.where(device_id: device_id) if device_id?
relation = relation.where(name: name) if name?
relation
end
private
def name?
name.present?... |
FactoryBot.define do
factory :comment do
advice_id { FactoryBot.create(:advice).id}
actor_id { FactoryBot.create(:user).id}
description { Faker::FunnyName.name_with_initial }
end
end
|
class User < ApplicationRecord
rolify
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
before_save :set_auth_token
private
d... |
class CharactersGame < ApplicationRecord
has_many :characters
has_many :games
end
|
require 'rubygems'
require 'digest/md5'
require 'bankjob'
module Bankjob
##
# A Transaction object represents a transaction in a bank account (a withdrawal, deposit,
# transfer, etc) and is generally the result of running a Bankjob scraper.
#
# A Scraper will create Transactions while scraping web pages in ... |
require 'todobot/responders/base_responder'
require 'todobot/message_sender'
module TodoBot
class UndefinedResponder < BaseResponder
def respond
TodoBot::MessageSender.new(bot: bot, chat: chat, text: I18n.t('undefined_command_type')).send
end
end
end
|
# == Schema Information
#
# Table name: houses
#
# id :integer not null, primary key
# address :string not null
# created_at :datetime
# updated_at :datetime
#
class House < ActiveRecord::Base
has_many :residents,
primary_key: :id,
foreign_key: :house_id,
class_name: "Person"... |
set :application, "splogna"
set :scm, :git
set :repository, "git://github.com/superchris/splogna.git"
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
set :deploy_to, "/home/christo0/apps/#{applicatio... |
class EventsController < ApplicationController
skip_before_action :authenticate_member!, :only => [:generate, :calendar, :index, :month]
helper :members
def show
@title = "Viewing Event"
@event = Event.find(params[:id])
authorize! :read, @event
end
def finance
@title = "Viewing Event Fina... |
class Book < ApplicationRecord
belongs_to :user
#attachment :image # ここを追加(_idは含めません)
validates :title, presence: true, length: {minimum: 2}
validates :body, presence: true, length: {maximum: 200}
end
|
require 'rails_helper'
RSpec.describe 'Microposts', type: :system, js: true do
describe '#new,#show,#destroy' do
context 'ログインしたとき' do
before do
@user = create(:user)
visit '/sign_in'
fill_in 'メールアドレス', with: @user.email
fill_in 'パスワード', with: @user.password
click_b... |
class MonthlyDistrictReport::Hypertension::BlockData
include MonthlyDistrictReport::Utils
attr_reader :repo, :district, :report_month, :last_6_months
def initialize(district, period_month)
@district = district
@report_month = period_month
@last_6_months = Range.new(@report_month.advance(months: -5), ... |
# ----------------------------------------------------------------------------------
# MIT License
#
# Copyright(c) Microsoft Corporation. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# nom :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
# birthdate :date
# rea... |
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :adjust_format_for_iphone
# before_filter :set_year
# before_filter :reload_settings
##
# Stuff to store and return to last recorded page
##
def remember_current_page(url=nil)
flash[:notice] = nil
flash[:... |
class ConnectionContextsController < ApplicationController
before_filter :authenticate_user!
def show
@application = Application.find(params[:application_id])
authenticate_ownership(@application)
@context = @application.connection_contexts.find(params[:id])
end
def edit
@application = Applica... |
require 'rspec'
require_relative 'find_and_replace'
describe FindAndReplacePath do
subject(:replacer) { described_class.new(find_pattern, replace_pattern) }
before do
@here = Dir.pwd
@there = '/tmp/find_and_replace_test_dir'
@file = "#{@there}/file.rb"
Dir.mkdir @there
Dir.chdir @there
end
... |
#encoding: utf-8
class WesellItem < ActiveRecord::Base
belongs_to :store
belongs_to :category
has_many :order_items, dependent: :restrict_with_exception
has_many :orders, through: :order_items
has_many :options_groups, dependent: :destroy
has_many :wesell_item_options
has_many :comments, dependent: :d... |
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
require 'set'
require 'dataMetaDom/util'
require 'dataMetaDom/recAttr'
require 'dataMetaDom/dataType'
require 'dataMetaDom/field'
require 'dataMetaDom/docs'
require 'dataMetaDom/enum'
... |
class Question < ActiveRecord::Base
attr_accessible :text, :adjectives
belongs_to :user
validates_presence_of :adjectives, :text
end
|
require './hash_keys'
describe Hash do
describe '#keys_of' do
it "should return the keys that match the values" do
expect({:a=> 1, :b=> 2, :c=> 3}).keys_of(1)).to eq([:a])
end
it "should return the keys that match the values" do
expect({:a=> 1, :b=> 2, :c=> 3, :d=> 1}).keys_of(1)).to eq(... |
class Thought
attr_reader :comment
def initialize
@comment = THOUGHTS.reduce('') { |carry, part| carry << part.sample + ' ' }.strip
end
THOUGHTS = [
[
'Es bonito',
'Me gusta',
'Lo mejor del mundo',
'Menos mal que puedo',
'Amo'
],
[
'encerrarme a ver Netflix',
... |
class Workplace < ActiveRecord::Base
attr_accessible :name
has_many :users
has_one :location
end
|
class UserResult
ERROR_TYPES = {
:duplicate => 'This email is already taken'
}.freeze
attr_reader :success, :error_reader
def initialize(success:, error_type: nil)
@success = success
@error_type = error_type
end
def success?
return @success
end
def duplicate?
return true if @err... |
module Vizier
class ExecutableUnit
def initialize(path, tasks)
@path = path
@tasks = tasks
@current_task = 0
@view = { "results" => [], "tasks" => {}, "subject" => {} }
@tasks.each do |task|
@view["tasks"][task.name] = {}
end
end
attr_reader :view, :path
d... |
module EmployeesHelper
#Developer : André & Frank
# return total salary of the given collection employees
def get_total_salaries(employees)
total = 0
employees.each do |e|
unless e.salary.nil?
total += e.salary
end
end
total.round(2)
end
# returns the average salary of th... |
class CreateOrders < ActiveRecord::Migration
def change
create_table :orders do |t|
t.integer :stock_id
t.string :productname
t.string :producttype
t.integer :productprice
t.integer :amount
t.integer :shippingfee
t.string :shippingway
t.string :shippingcode
t.... |
# frozen_string_literal: true
module Exceptions
# Base Json Api Exception
class NotAuthorized < Base
def errors
{
code: 401,
status: :unauthorized,
title: 'Not Authorized',
detail: @exception,
id: 401
}
end
end
end
|
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val = 0, left = nil, right = nil)
# @val = val
# @left = left
# @right = right
# end
# end
# @param {Integer[]} preorder
# @param {Integer[]} inorder
# @return {TreeNode}
def bu... |
class Student
attr_reader :first_name
@@all = []
def initialize(first_name)
@first_name = first_name
@@all << self
end
def self.all
@@all
end
def add_boating_test(test_name, status, instructor)
BoatingTest.new(self, test_name, "pending", instructor)
end
... |
class AddCompanyNameToEnquiries < ActiveRecord::Migration[5.2]
def change
add_column :enquiries, :company_name, :string
add_column :enquiries, :company_reg, :string
add_column :enquiries, :industry, :string
add_column :enquiries, :size, :string
add_column :enquiries, :location, :string
end
end
|
class Deck
attr_accessor :cards
def initialize
@cards = []
set_deck
end
def set_deck
Card::SUITS.each do |suit|
Card::RANKS.each do |rank, nominal|
card = Card.new(suit, rank, nominal)
@cards << card
end
end
end
def mix_deck
@cards.shuffle!
end
def giv... |
class JobApplicationsController < ApplicationController
before_filter :is_employer_exist_in_session, :only => [:call_for_interview]
def update
@job_application = JobApplication.includes(:job_seeker).find(params[:id])
@employer = Employer.find(session[:id])
@job_seeker = @job_application.job_seeker
... |
require_relative 'produser_module.rb'
class Train
include Produser
attr_reader :type, :id, :station_index, :current_staion, :route_stations
@@trains = {}
def initialize(id, type)
@id = id
@type = type
@speed = 0
@waggons = []
@waggons_count = 0
@route_stations = []
@current_staion = ni... |
require 'capybara/rspec'
require 'text_order/rspec'
RSpec.describe 'RSpec matchers', type: :feature do
STRING = 'first middle last'
describe 'after' do
it 'detects value after expected text' do
expect(STRING).to include_text('last').after('first')
end
end
describe 'before' do
it 'detects va... |
require 'test_helper'
class CommercegateTest < Test::Unit::TestCase
def setup
@gateway = CommercegateGateway.new(
:login => 'usrID',
:password => 'usrPass'
)
@credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'John'... |
module Translatable
extend ActiveSupport::Concern
DEFAULT_LOCALE = 'de'.freeze
TRANSLATABLE_LOCALES = ['ar', 'en', 'es', 'fa', 'fr', 'ku', 'pa', 'ps', 'ru', 'sq', 'sr', 'ti', 'tr', 'ur'].freeze
AREAS = Area.order(:id).pluck(:title).freeze rescue ['dresden', 'leipzig', 'bautzen'].freeze
# test flag, phrasea... |
json.array! @users_and_groups do |profile|
json.id profile.id
json.name profile.name
json.image_url profile.avatar_url(50)
json.link_url polymorphic_path(profile)
json.model_name profile.class.name
end
|
# encoding: utf-8
class FoodCalory < ActiveRecord::Base
def self.parse_amount( amount )
if pair = amount.match(/([1-9]+)\/([1-9]+)/)
origin, child, mother = pair.to_a
return (child.to_f / mother.to_f)
end
amount.to_f
end
def self.change_fraction( amount )
{
"½" => "1/2",
... |
require 'rails_helper'
def delete_post(post)
find(delete_post_selector).click
end
def edit_post_text(post, new_post_text)
find(edit_post_selector).click
fill_in "Body", with: new_post_text
click_on "Update Post"
end
def edit_post_picture(post, new_file_path)
find(edit_post_selector).click
attach_file "Pi... |
module Pacer::Core::Graph
# Basic methods for routes that contain only edges.
module EdgesRoute
import com.tinkerpop.pipes.transform.OutVertexPipe
import com.tinkerpop.pipes.transform.InVertexPipe
import com.tinkerpop.pipes.transform.BothVerticesPipe
# Extends the route with out vertices from this... |
require 'spec_helper'
class ClassB; extend Questionnaire::FieldsHelper; end
describe Questionnaire::FieldsHelper do
let(:questionnaire_section) { { "section_name" => { "some_field" => nil, "some_other_field" => nil } } }
let(:questionnaire_with_two_sections) { questionnaire_section.merge("second_section" => {"sec... |
class AddressesController < ApplicationController
def new
@address = Address.new
end
def create
@address = Address.new(save_params)
if @address.save
redirect_to new_card_path
else
render "new"
end
end
private
def save_params
params.require(:address).permit(:last_name... |
class TransferParticipantToUser
def initialize(participant:, user:, adapter: TwilioAdapter.new)
@participant = participant
@user = user
@adapter = adapter
end
def call
result = adapter.update_call(update_call_args)
if result
Result.success
else
Result.failure("Failed to upda... |
class ConvertPreptimeToIntegerOnRecipes < ActiveRecord::Migration
def up
add_column :recipes, :baking, :integer, default: 0
add_column :recipes, :cooling, :integer, default: 0
add_column :recipes, :rest, :integer, default: 0
add_column :recipes, :cooking, :integer, default: 0
end
def down
... |
FactoryGirl.define do
# DD: 'product' comes from Spree core, simple_product no longer exists
factory :subscribable_product, :parent => :product do
subscribable true
end
end
|
require 'spec_helper'
# FIXME: This is the worst spec I'v ever written. Magical and hackish, pls improve it.
describe DataMapper::Mongo::Adapter,'#connection' do
let(:object) { described_class.new(:default,options) }
subject { object.send :connection }
shared_examples_for 'a mongo connection setup' do
it ... |
class CreateCreditCardServices
def initialize(params)
@params = params
@params[:last4] = resolve_last4
end
def create
credit_card = initial_credit_card
encrypt_fields(credit_card)
credit_card.save ? credit_card : credit_card.errors.full_messages
end
private
def resolve_last4
@par... |
class Gender < ActiveRecord::Base
has_and_belongs_to_many :targets
has_many :members
has_many :participant_surveys
default_scope order('position asc')
end
|
module Stylin
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path("../../templates", __FILE__)
desc "Installs Stylin ready for use."
def install
copy_file "stylin.yml", "config/stylin.yml"
empty_directory "app/styleguides"
route "mount Stylin::Engine => '/style... |
require "rails_helper"
RSpec.feature "Transactions", :type => :feature do
scenario "User borrows $500 on day one" do
user = User.create(first_name: 'Bill', last_name: 'Miller', email: 'bill.miller@example.com', password: 'password')
visit root_path(as: user)
click_link 'Withdraw'
fill_in 'Amount',... |
class RemoveShopsFromUsers < ActiveRecord::Migration[5.1]
def change
remove_reference :users, :shop, foreign_key: true
end
end
|
require 'test_helper'
class BadgeTest < ActiveSupport::TestCase
self.use_instantiated_fixtures = true
fixtures :badges
def setup
@c = Client.find(:first)
@bi = BadgeImage.find(:first)
end
def test_create
b = Badge.new(:client_id => @c.id, :name => 'first time', :description => 'welcome, new ... |
require 'rails_helper'
class FactoryBot::Factory::Find
def association(runner)
runner.run
end
def result(evaluation)
query = get_overrides(evaluation)
result = build_class(evaluation).where(query).first
result
end
private
def build_class(evaluation)
evaluation.instance_variable_get(:... |
require 'mongo'
require_relative '../../../lib/recommendations/model/preference'
require_relative '../../../lib/recommendations/model/preferences'
require_relative '../../../lib/caching/cacheable'
module Recommendations
module DataModel
class MongoDataModel
include Cacheable
DEFAULT_HOST = "localhost... |
require 'rails_helper'
RSpec.describe Discount, type: :model do
describe "relationships" do
it { should have_many :discount_items}
it { should have_many(:items).through(:discount_items)}
end
describe "instance methods" do
it ".apply_discount" do
@merchant_1 = Merchant.create!(name: 'Megans Mar... |
require 'spec_helper'
describe MoviesHelper do
context "#days" do
describe "When we want to show 5 days in to the future for movies" do
describe "When no date has been chosen" do
before(:each) do
@days = days(5.days.from_now.localtime.to_s, 'bondijunction')
@days_as_document = ... |
require "capybara/poltergeist/errors"
require "capybara/poltergeist/command"
require 'json'
require 'time'
module Capybara::Poltergeist
class Browser
ERROR_MAPPINGS = {
'Poltergeist.JavascriptError' => JavascriptError,
'Poltergeist.FrameNotFound' => FrameNotFound,
'Poltergeist.InvalidSelector... |
class RemoveEmailAndPasswordDigestInLeadsModel < ActiveRecord::Migration
def up
remove_column :leads, :email
remove_column :leads, :password_digest
end
def down
add_column :leads, :email, :string
add_column :leads, :password_digest, :string
end
end
|
# Encoding: utf-8
require 'spec_helper'
describe 'kibana' do
describe file('/opt/kibana') do
it { should be_directory }
end
end
|
require 'rails_helper'
describe Card do
describe '#create' do
it "項目がすべて存在すれば登録できること" do
user = create(:user)
card = build(:card)
expect(card).to be_valid
end
it "user_idがない場合は登録出来ないこと" do
card = build(:card, user_id: nil)
card.valid?
expect(card.errors[:user]).to inc... |
class RecordRingGroupVoicemailGreetingMutation < Types::BaseMutation
description "Saves the provided audio as the voicemail greeting message for the ring group"
argument :ring_group_id, ID, required: true
argument :audio,
Types::ActiveStorageSignedIdType,
description: "The signed id of the audio file",
... |
#encoding: utf-8
module Orthography
REPLACES=[['Амортиз стойка', 'Амортизаторная стойка'],
['Амморт', 'Амортизатор'],
['АммортS ', 'Амортизатор '],
['Амортиз ', 'Амортизатор '],
['Башмак натажителя', 'Башмак натяжителя'],
['Болт-секр.', 'Болт секретка'],
['Гидрокрректор', 'Гидрокорр... |
#encoding: utf-8
class Member < ActiveRecord::Base
PAYMENT_PERIODS = [ :yearly, :monthly]
PAYMENT_METHODS = [ :direct_debit, :bank_transfer]
has_many :children, dependent: :destroy
has_one :bank_account, dependent: :destroy
has_many :membership_fees, dependent: :destroy
attr_accessible :beitrag, :email, :... |
# encoding: utf-8
# copyright: 2016, you
# license: All rights reserved
# date: 2016-09-16
# description: The Microsoft Internet Explorer 11 Security Technical Implementation Guide (STIG) is published as a tool to improve the security of Department of Defense (DoD) information systems. Comments or proposed revisions to... |
class AddUniqueIndexToTextFiles < ActiveRecord::Migration
def change
add_index :text_files, :URL, :unique => true
end
end
|
class House < Sequel::Model(DB)
class List < Trailblazer::Operation
extend Contract::DSL
step Contract::Build()
step Contract::Validate()
step :list_by_user_id
failure :log_failure
contract do
property :user_id, virtual: true
validation do
required(:user_id).filled
... |
# frozen_string_literal: true
class Addition < ApplicationRecord
has_attached_file :data
validates_attachment_content_type :data, content_type: 'text/plain'
validates_attachment_presence :data
end
|
# A controller which performs task related logic.
class TasksController < ApplicationController
# Loads the task specified by the id given in the url before update and destroy action is performed.
before_action :load_task, only: %i[update destroy]
# Returns all the tasks created by the user as an array of custom... |
require 'krypt'
class MyProvider
def new_service(clazz, *args)
if clazz == Krypt::Digest && args[0] == "identity"
IdentityDigest.new
else
nil
end
end
def name
"MyProvider"
end
def finalize
end
end
class IdentityDigest
def initialize
reset
end
def reset
@bu... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
respond_to :html, :json
rescue_from Contentful::BadRequest, :with => :not_found
def not_found(exception)
respond_to do |format|
format.json { render json: { status: "error", message: exception.message }, statu... |
require 'spec_helper'
RSpec.describe 'Game' do
let(:response) { JSON.parse(last_response.body) }
before do
header 'CONTENT_TYPE', 'application/json'
post '/game', { player1: 'foo', player2: 'bar' }.to_json
end
describe 'POST /game' do
context 'when I create a game' do
it { expect(last_respon... |
require 'rails_helper'
describe "Api::V1::Posts", type: :request do
let(:title) { 'this is a title' }
let(:content) { 'article content' }
let(:description) { 'this is a cool description' }
let(:image) { nil }
let(:attrs) do
{
title: title,
content: content,
description: description,
... |
class VirtualAssistantsController < ApplicationController
# GET /virtual_assistants
# GET /virtual_assistants.json
def index
@virtual_assistants = VirtualAssistant.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @virtual_assistants }
end
end
# GET /... |
class Video
attr_accessor :title, :duration, :genre, :rating
@@all = []
def initialize(title, duration, genre, rating)
@title = title
@duration = duration
@genre = genre
@rating = rating
end
def save
self.class.all << self
end
def self.all
@@all
end
def self.create(title, ... |
class AddSeasonToDivisions < ActiveRecord::Migration[5.2]
def change
add_reference :divisions, :season, foreign_key: true
end
end
|
# encoding: UTF-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... |
require_relative 'word_guess'
describe WordGuess do
let(:secret) {WordGuess.new("hello")}
it "converts number of words to '-'" do
expect(secret.word_convert).to eq "-----"
end
it "replaces '-' with correct letter" do
secret.word_convert
expect(secret.guess("h")).to eq "h----"
end
end |
require 'active_support/concern'
module RelationshipBulk
extend ActiveSupport::Concern
module ClassMethods
def bulk_update(ids, updates, team)
if updates[:action] == 'accept'
source_id = updates[:source_id]
pm_source = ProjectMedia.find_by_id(source_id)
# SQL bulk-update
... |
require 'spec_helper'
describe 'cassandra::agent' do
let(:params) do
{
:opscenter_ip => '192.168.2.1',
:opscenter_version => '5.0.1',
}
end
it 'does contain class cassandra::agent' do
should contain_class('cassandra::agent').with({
:opscenter_ip => '192.168.2.1',
:opsc... |
class Item < ApplicationRecord
validates :item_cat_id, :name, :code, presence: true
belongs_to :item_cat
has_many :store_items
has_many :retur_items
has_many :order_items
has_many :transaction_items
has_many :grocer_items
has_many :supplier_items
belongs_to :edited_by, class_name: "User", foreign_key... |
# filename: test_remove.rb
require "minitest/autorun"
require_relative "../../tile_group.rb"
##
# tests the hand method
class TestHand < Minitest::Test
# instantiating a new tile group
# like an @Before in JUnit4
def setup
@newTileGroup = TileGroup.new
end
# unit tests for the TileGroup:... |
class PositionLayout < Draco::System
filter LayoutGrid
def tick(args)
return if entities.nil?
entities.each do |layout|
current = world.scene || world
parent = current.entities[layout.tree.parent_id].first
#GTK::Log.puts_once layout.id, parent.inspect
#next unless parent
#... |
class IssueLink
attr_reader :issue, :view_context
def initialize(issue, view_context, options={})
@issue = issue
@view_context = view_context
end
def attributes
{
title: issue.title,
url: issue.link,
published_at: issue.published_at.strftime("%Y-%m-%d")
}
end
def render
... |
# prereqs: iterators, hashes, conditional logic
# Given a hash with numeric values, return the key for the smallest value
def key_for_min_value(name_hash)
return nil if name_hash.empty?
name = name_hash.first.first
smallest_val = name_hash.first.last
name_hash.each do |k, v|
if smallest_val > v
... |
require 'unit_spec_helper'
describe HandleRecurrences do
let(:service) { HandleRecurrences.new }
context "#recurrences" do
it 'fetches all recurrences' do
Recurrence.expects(:ready)
service.recurrences
end
end
context "#perform" do
before do
service.stubs(:recurrences).returns(r... |
class AddPhysicalLocationRelationBetweenSitesAndCountries < ActiveRecord::Migration[5.2]
def change
create_table :physical_locations do |t|
t.belongs_to :site, index: true
t.belongs_to :country, index: true
t.timestamps
end
end
end
|
class StaticController < ApplicationController
def index
if current_user
@users_households = Household.where(id: Householdmembers.where(member: current_user.id).pluck("hhid")).order("id DESC")
end
end
end
|
class GameSerializer < ActiveModel::Serializer
embed :ids, include: true
attributes :id, :state, :player_cards, :dealer_cards, :player_score, :dealer_score, :winner, :bet
has_one :user
has_many :cards
has_one :game_session
def cards
object.game_session.decks.map { |deck| deck.played_cards }.flatten
e... |
assert_throws NoExperienceError { employee.hire }
|
# MTA Lab
#
# Activity:
#
# Students should create a program that models a simple subway system.
#
# The program takes the line and stop that a user is getting on at and the line and stop that user is getting off at and prints:
#
# the stations the user must pass through, in order
# where to change lines, if necessary
... |
class Users::Lawyer < User
def devise_mapping_override
:lawyer
end
end
|
require 'rspec'
require 'spec_helper'
describe 'Estrella' do
it 'deberia almacenar vida cuando se instancia el objeto' do
estrella = Estrella.new 70, 0
expect(estrella.vida).to eq 70
end
it 'deberia almacenar masa cuando se instancia el objeto' do
estrella = Estrella.new 100, 45
expect(estrel... |
require "rake/testtask"
Rake::TestTask.new do |t|
t.description = "Run integration and unit tests"
t.libs << "test"
t.pattern = File.join("test", "**", "test_*.rb")
t.warning = false
end
namespace :test do
mock = ENV["FOG_MOCK"] || "true"
task :travis do
sh("bundle exec rake test:unit")
end
desc ... |
#!/usr/bin/env ruby
require 'base64'
require 'openssl'
class ConvertCookie
# Encode session cookies as Base64
class Base64
def encode(str)
[str].pack('m').gsub(/\n/, '')
end
def decode(str)
str.unpack('m').first
end
# Encode session cookies as Marshaled Base64 data
class Mar... |
#!/usr/bin/ruby -w
#
# Test miscellaneous items that don't fit elsewhere
#
require File.expand_path('etchtest', File.dirname(__FILE__))
require 'webrick'
class EtchMiscTests < Test::Unit::TestCase
include EtchTests
def setup
# Generate a file to use as our etch target/destination
@targetfile = released_... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
protected
def restrict_access
if !current_user
puts 'here'
flash[:alert] = "You must be logged in."
redirect_to '/'
end
end
def current_user
@current_user || User.find(... |
Rails.application.routes.draw do
mount RailsAdmin::Engine => '/admin', as: 'rails_admin'
get '/', to: 'welcome#index'
devise_for :users, skip: [:sessions]
as :user do
get '/login', to: 'devise/sessions#new', as: :new_user_session
post '/login', to: 'devise/sessions#create', as: :user_session
get '... |
class UncompleteSkill
include Interactor
def setup
context.fail!(message: "provide a valid user") unless context[:user].present?
context.fail!(message: "provide a valid skill") unless context[:skill].present?
if !failure? && !context[:user].has_completed?(context[:skill])
context.fail!(message: ... |
require 'geo_ruby/geojson'
require 'phone'
require 'sequel'
ENV['DATABASE_URL'] ||= "postgres://localhost/citygram_#{Citygram::App.environment}"
DB = Sequel.connect(ENV['DATABASE_URL'])
Sequel.default_timezone = :utc
# no mass-assignable columns by default
Sequel::Model.set_allowed_columns(*[])
# use first!, create... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.