text stringlengths 10 2.61M |
|---|
class CompanyController < ApplicationController
before_action :check_user, except: [:register]
before_action :set_company, only: [:accept, :edit, :destroy, :edit_logo]
def register
if Company.find_by(name: company_params[:name]).nil?
@company = Company.new(company_params)
if @company.save
@user = @com... |
require 'spec_helper'
module Songkick
module Transport
describe HttParty do
class FakeJSONException < Exception; end
let(:request){ Request.new('http://localhost', 'get', '/', {}) }
describe 'handling errors' do
class FakeHttparty < Songkick::Transport::HttParty::Adapter
cl... |
class StaffRegistrationsController < Devise::RegistrationsController
def create
@staff = Staff.new(sign_up_params)
respond_to do |format|
if @staff.save
sign_in(@staff)
format.html { redirect_to new_profile_path, notice: "Staff has been created. Now create a profile for the staff."}
... |
module ShopifyImport
module DataParsers
module Users
class BaseData
def initialize(shopify_customer)
@shopify_customer = shopify_customer
end
def user_attributes
{
created_at: @shopify_customer.created_at,
email: @shopify_customer.email,
... |
# Which of these two classes has an instance variable and how do you know?
class Fruit
def initialize(name)
name = name
end
end
class Pizza
def initialize(name)
@name = name # => the @ at the beginning of the variable name means it is an instance variable
end
end
hot_pizza = Pizza.new("cheese")
oran... |
require "spec_helper"
feature "user invites a friend" do
scenario "successfully and invitation is accepted" do
user = Fabricate(:user)
sign_in_user user
invite_a_friend
signout
friend_accepts_invitation
friend_fills_in_registration
check_account_is_following user.full_name
signout
... |
# frozen_string_literal: true
namespace :v2 do
desc "Fetch all origin with github_history data"
task download_github_history_origins: :environment do
ActiveRecord::Base.logger = nil if Rails.env.production?
origins = ::V2::Origin.where(data_category: "github_history")
origins.each do |origin|
::V... |
class Address < ActiveRecord::Base
belongs_to :cinema
belongs_to :film
end
|
class Store < ActiveRecord::Base
has_many :employees
validates :name, length: {minimum: 3}
validates :annual_revenue, numericality: { greater_than_or_equal_to: 0}
validate :must_carry_mens_or_womens_apparel
def must_carry_mens_or_womens_apparel
if !(mens_apparel || womens_apparel)
errors.add(:me... |
# WhatITake
module WhatITake
#Tecla atalho para exebição da janela
TECLA_ATALHO="CTRL+ALT+d"
def var_dump(var)
html="<div style='padding-left:10px;'>"
begin
html<< "#{h(var.to_yaml).gsub(" ", " ").gsub("\n\n", "<br/>" ).gsub("\n", "<br/>" ).gsub("---", "" )}"
rescue Object => e
html << " #{h(var... |
class CreateCommodities < ActiveRecord::Migration
def change
create_table :commodities do |t|
t.string :commodity_name
t.string :variety
t.float :temp_low
t.float :temp_high
t.float :lat1
t.float :lat2
t.integer :elevation_low
t.integer :elevation_high
t.strin... |
class ForsController < ApplicationController
before_action :set_for, only: [:show, :edit, :update, :destroy]
# GET /fors
# GET /fors.json
def index
@fors = For.all
end
# GET /fors/1
# GET /fors/1.json
def show
end
# GET /fors/new
def new
@for = For.new
end
# GET /fors/1/edit
def ... |
class CreateWeaknesses < ActiveRecord::Migration
def self.up
create_table :weaknesses do |t|
t.string :name, :limit => 255
t.integer :weakness_type
t.integer :count
t.float :score
end
end
def self.down
drop_table :weaknesses
end
end
|
class Graph
def initialize(nv, edges)
@nvertices = nv
@adjmat = nv.times.collect { Array.new(nv, 0) }
edges.each do |i, j, w|
@adjmat[i][j] = w
end
end
def each_vertices
@nvertices.times do |i|
yield i
end
end
def each_edges
... |
require 'spec_helper'
describe('puppetsymlink', :type => :class) do
context 'Unsupported OS' do
let(:facts) { { :kernel => 'Windows' } }
it do
expect { should compile }. to raise_error
end
end
context 'Linux - Agent' do
let(:facts) { { :kernel => 'Linux', :symlinkexecutables => ["hie... |
namespace :twit do
desc "Generate 10 twits (twit:generate[10])"
task :generate, [:count] => :environment do |t, args|
args[:count].to_i.times do |i|
twit = Twit.new(body: Faker::Lorem.sentence)
twit.tags.build(name: Faker::Lorem.word)
twit.save!
end
end
end
|
require "spec_helper"
require "json"
describe Eshealth::ClusterHealth do
describe "Attributes" do
clusterhealth = Eshealth::ClusterHealth.new
describe ".url" do
it "Allows reading and writing for :url" do
clusterhealth.url = "something_stupid"
expect(clusterhealth.url).to eq("something_... |
class River
#attr_accessor :fishies
def initialize(fishies)
@fishies = fishies
end
def count_fish
return @fishies.length
end
def get_fish
@fishies.pop()
end
end |
require File.dirname(__FILE__) + '/../test_helper'
class WikiTest < Test::Unit::TestCase
fixtures :wikis, :wiki_pages
def setup
@wiki = Wiki.find 1
end
# Replace this with your real tests.
def test_accessors
assert_not_nil @wiki
assert_kind_of Wiki, @wiki
assert_equal "Wikipedia (en)", @wik... |
class AddIndexToInstitutionsName < ActiveRecord::Migration
def change
add_index :institutions, :name, unique: true
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe RegistrationOption do
let(:user) { create(:user) }
let(:event) { create(:event) }
let(:event_selection) { create(:event_selection, event: event, description: 'An Option') }
let!(:event_option) { create(:event_option, event_selection: event_s... |
if Rails.env.development?
Shoryuken.configure_client do |config|
Rails.logger = Shoryuken::Logging.logger
Rails.logger.level = Rails.application.config.log_level
config.sqs_client = Aws::SQS::Client.new(
endpoint: ENV["SQS_SERVER_MOCK_URL"],
verify_checksums: false
... |
class Dashboard < ActiveRecord::Base
has_many :users
has_many :uploads, dependent: :destroy
has_many :news_feeds, dependent: :destroy
validates :user_id, presence: true
def set_user(user)
self.user_id = user.id
end
end
|
class Section < ActiveRecord::Base
# attr_accessible :title, :body
belongs_to :page
has_many :section_edits
has_many :editors, :through => :section_edits, :class_name => "AdminUser"
attr_accessible :name, :permalink, :position, :visible
end
|
=begin
#qTest Manager API Version 8.6 - 9.1
#qTest Manager API Version 8.6 - 9.1
OpenAPI spec version: 8.6 - 9.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require "uri"
module SwaggerClient
class FieldApi
attr_accessor :api_client
def initialize(api_client =... |
module TestLauncher
module Utils
module Pluralize
def pluralize(count, singular)
phrase = "#{count} #{singular}"
if count == 1
phrase
else
"#{phrase}s"
end
end
end
end
end
|
require_relative "sales_engine"
require "ruby_prof"
require "pry"
class SalesEngineProfiler
TIMEOUT_THRESHOLD = 15 #seconds
attr_reader :data_dir, :engine
def initialize(data_dir)
@data_dir = data_dir
end
def profiled(&block)
RubyProf.start
begin
yield block
rescue
puts "OOPS WE... |
require 'spec_helper'
feature 'Send newsletter to collaborators' do
let!(:organization) { new_organization }
let!(:challenge) { FactoryBot.create(:challenge, organization: organization) }
let!(:members) { FactoryBot.create_list(:user, 5).map(&:userable) }
background do
sign_in_user(organization.user, pass... |
require 'sequel'
module Datoki
UTC_NOW_DATE = ::Sequel.lit("CURRENT_DATE")
UTC_NOW_RAW = "timezone('UTC'::text, now())"
UTC_NOW = ::Sequel.lit("timezone('UTC'::text, now())")
Invalid = Class.new RuntimeError
Schema_Conflict = Class.new RuntimeError
Actions = [:all, :create, :read, :... |
class User < ActiveRecord::Base
validates :email, presence: true
validates :email, uniqueness: true
has_many :products
def self.last_created_users(limit)
limit(limit).order(created_at: :desc)
end
end
|
class CreateDueDays < ActiveRecord::Migration[5.2]
def change
create_table :due_days do |t|
t.string :type_of_book
t.integer :due_days
t.timestamps
end
end
end
|
class Survey < ActiveRecord::Base
has_many :questions
has_many :completed_surveys
belongs_to :user
validates :name, uniqueness: true
# Remember to create a migration!
end
|
RSpec.describe King, type: :model do
before(:all) do
@white_player = create(:user)
@black_player = create(:user)
end
before(:each) do
@game = create(:game)
@game.white_player_id = @white_player.id
@game.black_player_id = @black_player.id
@game.save
end
context 'movement t... |
class PrelovedAdvert
attr_reader :id, :title, :description, :image
def initialize(id, title, description, image)
@id = id
@title = title
@description = description
@image = image
end
def short_desc
#if @description.length > 72
# @description.gsub(/\r?\n/, "")[0, 72] + "..."
#else... |
require "test_helper"
require "test_launcher/searchers/git_searcher"
module TestLauncher
module Searchers
class MockShell
def run(cmd)
if cmd == "git ls-files '*file_pattern*'"
[
"file/path/one.rb",
"another_file/path/two.rb",
]
elsif cmd == "git ... |
class Answer < ActiveRecord::Base
validates :text, :presence => true
belongs_to :user
belongs_to :question
has_many :comments, dependent: :destroy
scope :daily, -> { where(created_at: Time.current.all_day) }
end
|
module Cultivation
class TrayPlan
include Mongoid::Document
include Mongoid::Timestamps::Short
field :facility_id, type: BSON::ObjectId
field :room_id, type: BSON::ObjectId
field :row_id, type: BSON::ObjectId
field :shelf_id, type: BSON::ObjectId
field :tray_id, type: BSON::ObjectId
f... |
# frozen_string_literal: true
def binary_search(arr, item)
low = 0
high = arr.size - 1
while low <= high
mid = (low + high) / 2
case item <=> arr[mid]
when 0
return mid
when -1
high = mid - 1
when 1
low = mid + 1
end
end
end
|
module Donors
class BloodCollectionFacilitiesController < ApplicationController
before_action :set_blood_collection_facility, only: %i[show]
# GET /donors/blood_collection_facilities
# GET /donors/blood_collection_facilities.json
def index
@blood_collection_facilities = BloodCollectionFacility.... |
module LoyaltyConnect
module Model
class Transaction < Struct.new(:id, :url, :merchant_name, :purchase_date, :brand, :last_4, :status, :amount, :currency, :reward_amount)
class << self
def from_json_hash(json_hash)
data = json_hash || {}
Transaction.new(
data['id'],
... |
require "spec_helper"
# These specs also passively test the +status_text+ method.
describe Concern::Methods::ContentStatusMethods do
describe "#killed?" do
it "is true if status is ContentBase::STATUS_KILLED" do
story = build :test_class_story, status: ContentBase::STATUS_KILLED
story.killed?.should... |
require 'test_helper'
class StringTest < ActiveSupport::TestCase
test "to channel name replace at and dots" do
assert_equal "lorem_plus_123_at_acme_dot_org_dot_ar", "lorem+123@acme.org.ar".to_channel_name
end
end
|
require 'spec_helper'
require 'cgi'
describe Gibbon do
describe "attributes" do
before do
Gibbon::APIRequest.send(:public, *Gibbon::APIRequest.protected_instance_methods)
@api_key = "123-us1"
@proxy = 'the_proxy'
end
it "have no API by default" do
@gibbon = Gibbon::Request.new
... |
class ItemImage < ApplicationRecord
belongs_to :item
mount_uploader :image_url, ImageUploader
validates :image_url, presence: true
def self.search(search)
if search != ""
ItemImage.where('name Like(?)', "%#{search}%")
else
ItemImage.all
end
end
end
|
# source: https://launchschool.com/exercises/098fba0b
# Q: Write a minitest assertion that will fail if the class of value is not
# Numeric or one of Numeric's subclasses (e.g., Integer, Float, etc).
def test_kind_of_value
assert_kind_of(Numeric, value)
end
|
FactoryGirl.define do
factory :address, class: Address do
creator
updater
factory :el_cerrito_address, aliases: [:el_cerrito] do
street '2000 San Pablo Blvd'
suite '#1500'
city 'El Cerrito'
state 'CA'
zip '95555'
end
end
factory :berkeley_address, class: Address do
created_by 1
updated_... |
module CamaleonCms
class ThemeDecorator < CamaleonCms::TermTaxonomyDecorator
delegate_all
def the_id
object.id
end
def the_settings_url
args = h.cama_current_site_host_port({})
h.cama_admin_settings_theme_url(args)
end
def the_settings_link
return '' unless h.cama_cu... |
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery with: :exception
# before_action :require_valid_user!
def current_user
if !session[:user_id].blank?
@user ||= User.find(session[:user_id])
end
end
def require_valid_user!
if current_user.nil?
flash[:error] = 'Yo... |
namespace :load do
require 'csv'
desc "load customers from csv"
task :customers => :environment do |t, arg|
['db/data/customers.csv'].each do |customer|
CSV.foreach(customer,:headers => true) do |row|
id = row.to_hash['id']
first_name = row.to_hash['first_name']
last_name = row.... |
#! /usr/bin/env ruby
####################################################################
DIR = File.dirname($0)
$: << File.join(DIR, 'lib')
####################################################################
require 'getoptlong'
require 'bio'
require 'process_species_name'
require 'Dir'
require 'processbar'
##... |
require_relative "./card_kind.rb"
module Model
class Hand
HAND_STATE_PLAYING = :hand_playing
HAND_STATE_BUSTED = :hand_busted
HAND_STATE_STAND = :hand_stand
HAND_STATE_DOUBLED_DOWN = :hand_doubled_down
def initialize(bet, cards, is_split_hand: false)
@state = HAND_STATE_PLAYING
@bet = bet
@cards... |
class RemovePolicyDetailsColumnFromPolicies < ActiveRecord::Migration
def change
remove_column :policies, :policy_details_type, :string
remove_column :policies, :policy_details_id, :integer
end
end
|
Given(/^I am on the google shopping page$/) do
visit('https://www.google.co.uk/shopping')
end
And(/^I search for "([^"]*)"$/) do |arg|
fill_in 'q', with: arg
page.find('#gbqfb').click
sleep(1)
end
Then(/^I get "([^"]*)" results$/) do |arg|
@page = GoogleShopping.new
@page.verify_search(arg)
end
When(/^I ... |
class FlappySwift < BrewSparkling::Recipe::Builder
github 'fullstackio/FlappySwift', branch: 'e4da5dc8a7228c000c6e245f965765bfbd905e58'
description 'swift implementation of flappy bird. More at fullstackedu.com https://www.fullstackedu.com'
version '1.0'
bundle_identifier 'io.fullstack.FlappyBird'
executable_... |
class CreateSumitomoData < ActiveRecord::Migration
def change
create_table :sumitomo_data do |t|
t.string :inventory_number, :quantity, :quantity_updated_type, :seller_cost, :dc_quantity
t.timestamps
t.timestamps
end
end
end
|
# encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
require "logstash/timestamp"
require "json"
require "date"
class LogStash::Filters::VarnishLog < LogStash::Filters::Base
# Setting the config_name here is required. This is how you
# configure this filter from your Logstash config.
#... |
class IncreasePromoBlurbLimitForHeroImages < ActiveRecord::Migration
def change
add_column :hero_images, :promo_blurb_location, :string, limit: 7
change_column :hero_images, :caption, :string, limit: 50
end
end
|
require 'spec_helper'
feature 'Gerenciar Desenvolvedor' do
before :each do
end
scenario 'Incluir Desenvolvedor' do
visit new_desenvolvedor_path
preencher_e_verificar_desenvolvedor
end
scenario 'Alterar Desenvolvedor' do #, :javascript => true do
desenvolvedor = FactoryGirl.create(:desen... |
require 'test/unit'
require 'wsdl/parser'
require 'wsdl/soap/wsdl2ruby'
require 'soap/rpc/standaloneServer'
require 'soap/wsdlDriver'
module WSDL; module Document
class TestNumber < Test::Unit::TestCase
class Server < ::SOAP::RPC::StandaloneServer
Namespace = 'urn:foo'
def on_init
add_document_meth... |
class StringMix
attr_reader :shared_letters
def lowercase_count(string)
letters = Hash.new(0)
string.chars.each do |char|
next if char.upcase == char
letters[char] += 1
end
letters
end
def mix(s1, s2)
s1_counts = lowercase_count(s1)
s2_counts = lowercase_count(s2)
@re... |
class CreateProductEdits < ActiveRecord::Migration
def change
create_table :product_edits do |t|
t.integer :variant_id, :limit => 8
t.integer :product_id, :limit => 8
t.string :image_source
t.string :title
t.string :title_new
t.string :description
t.string :description_n... |
require_relative "tile.rb"
require_relative "board.rb"
class Game
def initialize(filename)
@board = Board.new(filename)
end
def play
until @board.solved?
@board.render
pos_prompt
pos = gets.chomp.split(",").map(&:to_i)
value_prompt
value = gets.chomp.to_i
handle_move... |
module Providers
class Sbobet < Base
URL_ROOT = "http://www.sbobet.com"
URL_LEAGUES_JS = '/en/resource/e/euro-dynamic.js?%s'
URL_BETLINES = '/euro/%s'
MAX_DOMAIN_FAILURES = 50
def initialize(sport = :soccer)
@time_zone = "Asia/Hong_Kong"
super(sport)
@domains = [
#{ url:... |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def current_user
@current_user ||= session[:user] && User.find(session[:user]) || User.guest rescue User.guest
en... |
require 'spec_helper'
describe Liquidize do
it 'has a version' do
expect(Liquidize::VERSION).not_to be_nil
end
end
|
class DosesController < ApplicationController
before_action :set_dose_cocktail, only: %i[new index show create]
before_action :set_dose, only: %i[destroy edit update]
def index
@doses = @cocktail.doses
end
def show; end
def new
@dose = Dose.new
end
def create
@dose = Dose.new(dose_params... |
# 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 rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
class AddHitCountToReviewHouse < ActiveRecord::Migration
def change
add_column :review_houses, :hit_count, :integer, default: 0
end
end
|
class BookmarksController < ApplicationController
@@tag_filter = ["the", "a"]
def index
# news feed / homepage
@bookmarks = Bookmark.all
# add bookmark search form in index file
end
def show
@bookmark = Bookmark.find(params[:id])
end
def results
@search_terms = params[:search_terms]
... |
require 'twitter_client'
class Prey < ActiveRecord::Base
has_and_belongs_to_many :stalkers
has_many :posts
validates :uid, :provider, presence: true
after_create :seed_posts
def self.last_post_uid(prey_uid)
posts = Prey.find_by(uid: prey_uid).posts
# this will return nil if the prey has not posted ... |
Rails.application.routes.draw do
resources :lessons
resources :disciplines
resources :courses
resources :lections
resources :homeworks
root 'index#index'
end
|
class AddPlatnostToPrices < ActiveRecord::Migration
def change
add_column :prices, :until, :date
end
end
|
class PageContent < ActiveRecord::Base
include Concerns::PageContent::Association
include Concerns::PageContent::Validation
include Concerns::PageContent::Method
after_save :add_event_job_on_public, :if => lambda { self.publish? && self.page.event? }
after_save :add_event_job_on_cancel, :if => lambda { self.... |
require './lib/messages'
class BattleshipMethods
include Messages
attr_reader :player_board,
:computer_board,
:computer_game_display,
:humanoid_game_display,
:grid_positions,
:player_guesses,
:comp_guesses
def initialize(player_... |
module Databases::Filters
extend ActiveSupport::Concern
included do
helper_method :filter_params
end
def databases
Database.filter filter_params
end
def filter_params
if params[:filter].present?
params.require(:filter).permit :name, :driver
else
{}
end
end
end
|
require 'poms/api/json_client'
require 'poms/api/request'
module Poms
module Api
# Creates lazy Enumerators to handle pagination of the Poms API and performs
# the request on demand.
module PaginationClient
module_function
def execute(request)
Enumerator.new do |yielder|
pa... |
# Copyright (c) 2009-2011 VMware, Inc.
require File.dirname(__FILE__) + "/spec_helper"
require "rabbit_service/rabbit_node"
module VCAP
module Services
module Rabbit
class Node
attr_reader :local_ip, :base_dir, :node_id, :capacity, :max_clients, :rabbitmq_server, :port_gap
attr_accessor ... |
# 5) Faça uma função chamada 'mediana' que recebe um array de números e retorna a mediana entre eles.
# Lembrando que para obter a mediana de uma série de números, é necessário ordenar a série (usar a função sort()) e retornar:
# - se a série tiver um número (n) ímpar de elementos, retornar o número da posição n/2 (a p... |
class UserNotifier < ActionMailer::Base
def signup_notification(user)
setup_email(user)
@subject += ' Please activate your new account'
@body[:code] = user.activation_code
@body[:url] = activate_url(:host => HOSTNAME, :activation_code => @body[:code])
end
def activation(user)
setup_ema... |
FactoryGirl.define do
factory :entry do
title "MyString"
content "MyString"
end
end
|
require 'rails_helper'
describe AlbumPolicy do
subject { described_class }
context 'for a visitor' do
let(:member) { nil }
let(:album) { FactoryGirl.create(:album) }
permissions :index?, :show?, :new?, :edit?, :create?, :update?, :destroy? do
it 'does not grant access for non logged in visitors' ... |
module Processes
module Instagram #Follow.new.run
include Identification
instagram = Platform::Instagr_am.new
db = Platform::Database.new
CLIENT, MY_ID = instagram.access
COLLECTION = db.get_connection.collection("tags")
def follow_count #posts numbers for follower counts
follow_by = CLIENT.us... |
class Player < ActiveRecord::Base
belongs_to :team
has_many :transfer
mount_uploader :avatar, PlayerAvatarUploader
end
|
class NweetsController < ApplicationController
before_action :authenticate_user!, except: [:show]
before_action :correct_user, only: [:update, :destroy]
def new
@nweet = current_user.nweets.build(did_at: Time.zone.now)
@feed_items = current_user.timeline.paginate(page: params[:page])
@timeline = true... |
# encoding: UTF-8
# extend matrix with method []=(i,j,v)
# usage: m = ::Matrix.scalar(size,value).extend(Vote::Matrix)
module Vote
module Matrix
def []=(i, j, v)
@rows[i][j] = v
end
end
end
|
class Team < ApplicationRecord
extend Enumerize
belongs_to :creator, class_name: 'User'
belongs_to :leader, class_name: 'User'
has_many :memberships, dependent: :destroy
has_many :members, through: :memberships, source: :user
enumerize :default_home,
in: DEFAULT_HOMES,
default: :campaigns
... |
class MyImage < ApplicationRecord
mount_uploader :image, ImageUploader
paginates_per 4
validates :name, uniqueness: true
validate :presence_of_image
def self.import(file)
response_hash = {}
imported_file = open_file(file)
header = imported_file.row(1)
if header.include?("name") and header.includ... |
class Api::ServicesController < ApiController
def index
@services = @organization.services
render json: @services
end
end
|
cd_zsh_path = ::File.expand_path(::File.join(ENV['HOME'],
'.oh-my-zsh/custom/cd_vagrant.zsh'))
file cd_zsh_path do
content 'cd /vagrant'
owner ENV['SUDO_USER'] || node['current_user']
action :create_if_missing
only_if { FueledZsh.installed? }
end
|
# -*- encoding : utf-8 -*-
# The business logic for donations to artists.
#
# 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 Lic... |
class AddScoreReductionColumn < ActiveRecord::Migration
def change
add_column :ratings, :last_reduction, :date
end
end
|
class CreateGoalSessions < ActiveRecord::Migration
def change
create_table :goal_sessions do |t|
t.belongs_to :creator
t.belongs_to :participant
t.belongs_to :goal
t.integer :score, default: 0
t.integer :likes_count, default: 0
t.integer :comments_count, default:... |
class User < ApplicationRecord
def self.from_github(data, access_token)
user = User.find_or_create_by(uid: data["id"])
user.username = data["login"]
user.avatar = data["avatar_url"]
user.token = access_token
user.save
return user
end
end
|
require(File.dirname(File.expand_path(__FILE__)) + '/../lib/to_json')
describe String do
it "should convert a string to json" do
"string".to_json.should == "\"string\""
end
it "should convert a number string into json" do
"1".to_json.should == "\"1\""
end
end
describe Fixnum do
it "should conver... |
# Copyright 2014 Square Inc.
#
# 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 ... |
class MentionTimelinesController < TimelineController
layout "user"
protected
def tweets
@tweets ||= Tweet.where("text LIKE ?", "%#{user.username.gsub('%', '%%')}%").order("tweets.created_at desc").offset(params[:page].to_i * 20).limit(20)
end
helper_method :tweets
def user
@user ||= User.find_by_u... |
class AddAbstractAndFullTextToArticles < ActiveRecord::Migration
def change
add_column :articles, :abstract, :text
add_column :articles, :full_text, :text
end
end
|
require "spec_helper"
describe Refunge::Interpreter do
attr_reader :interpreter
context "on initialize" do
before(:each) do
@interpreter = described_class.new(" ")
end
it "should set the cursor at 0, 0" do
expect(interpreter.cursor).to eq([0, 0])
end
it "should set the initial di... |
require 'spec_helper'
describe Kata::Algorithms do
describe '.odd_occurrences' do
[
[[9, 3, 9, 3, 9, 7, 9], 7],
[[9, 3, 9, 8, 3, 9, 7, 9, 7], 8],
[[7], 7],
].each do |input, output|
it "when input is #{input} then output is #{output}" do
expect(described_class.odd_occurr... |
# frozen_string_literal: true
module Types
module Home
class Cases < Types::BaseObject
field :label, String, null: false
field :name, String, null: false
field :value, Int, null: false
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.