text stringlengths 10 2.61M |
|---|
Rails.application.routes.draw do
root "home#index"
get :login, to: "sessions#new", as: :login
post :login, to: "sessions#create"
delete :logout, to: "sessions#destroy", as: :logout
get :register, to: "users#new", as: :register
post :register, to: "users#create"
resources :users, only: %i(new create)
... |
require 'spec_helper'
describe Player do
describe '#initialize' do
it 'creates a player object with a readable name and a readable array for holding cards' do
my_player = Player.new(name: "John")
expect(my_player.name).to eq "John"
expect(my_player.cards).to eq []
end
it 'defaults to A... |
#encoding: utf-8
# Copyright (c) 2013-2014, Sylvain LAPERCHE
# All rights reserved.
# License: BSD 3-Clause (http://opensource.org/licenses/BSD-3-Clause)
require 'test/unit'
require 'netcdf'
include NetCDF
class TestDataset < Test::Unit::TestCase
#--------------#
# Dataset::new #
#--------------#
def test_n... |
require 'rails_helper'
RSpec.describe SqueaksController, type: :controller do
describe 'get#index' do
it 'renders the squeaks index' do
allow(subject).to receive(:logged_in?).and_return(true)
# this line mimicks a logged in user
get :index
# type of request, then action to hit
... |
class ChangeApplicationsToCandidacies < ActiveRecord::Migration[5.2]
def change
rename_table :applications, :candidacies
end
end
|
class CreateStudyListItems < ActiveRecord::Migration
def change
create_table :study_list_items do |t|
t.integer :study_list_id, null: false
t.string :front
t.string :back
t.string :images
t.boolean :pav, default: false
t.boolean :kav, default: false
t.timestamps
end
... |
require 'rails_helper'
describe Report do
describe 'workaround parsing bug in Rack or Rails for multi-select box' do
it "should handle ['3','4','5']" do
Report.list_of_ints_from_multiselect( ['3','4','5'] ).should == [3,4,5]
end
it "should handle ['3,4,5']" do
Report.list_of_ints_from_multise... |
CitizenshipApp::Application.routes.draw do
resources :questions
resources :users
resources :sessions, only: [:new, :create, :destroy]
root 'static_pages#home'
match '/signup', to: 'users#new', via: 'get'
match '/signin', to: 'sessions#new', via: 'get'
match '/signout... |
require 'couchrest'
class Copier
def initialize src_db, dst_db
@src_db, @dst_db = src_db, dst_db
end
# copy src_doc and all attachments, dst_doc is the current doc in the dst_db
def copy src, old_dst = nil
# get source doc if src is a string (key)
src_doc = src.is_a?(String) ? @src_db.get(src) :
... |
#
# Testing rufus-verbs
#
# jmettraux@gmail.com
#
# Sun Jan 13 12:33:03 JST 2008
#
require File.dirname(__FILE__) + '/base.rb'
class ItemConditionalTest < Test::Unit::TestCase
include TestBaseMixin
include Rufus::Verbs
def test_0
require 'open-uri'
f = open "http://localhost:7777/items"
d = f... |
require 'spec_helper'
require 'timecop'
RSpec.describe Raven::ClientState do
let(:state) { Raven::ClientState.new }
it 'should try when online' do
expect(state.should_try?).to eq(true)
end
it 'should not try with a new error' do
state.failure
expect(state.should_try?).to eq(false)
end
it 'sh... |
module SMSFuHelper
# Returns a collection of carriers to be used in your own select tag
# e.g., <%= f.select :mobile_carrier, carrier_collection %>
def carrier_collection
SMSFu.carriers.sort.collect{ |carrier| [carrier[1]["name"], carrier[0]] }
end
# Returns a formatted select box filled with carrier... |
class UsersController < ApplicationController
skip_before_filter :login_required, only: [:new, :create]
# GET /users
# GET /users.json
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET... |
class Alert < ApplicationRecord
self.inheritance_column = :alert_type
enum status: { active: 'active', archived: 'archived', errored: 'errored' }
belongs_to :user
before_create :generate_uuid
scope :search, -> { where(alert_type: 'Alert::Search') }
scope :bill, -> { where(alert_type: 'Alert::Bill') }
... |
module CollinsNotify
class CommandRunner
def run args
app = CollinsNotify::Application.new
begin
app.configure! args
get_contact_and_asset app, true # throws exception if not configured properly
rescue SystemExit => e
exit e.status
rescue CollinsNotify::Configurat... |
class CatRentalRequest < ApplicationRecord
validates: :status, inclusion: %w(PENDING APPROVED DENIED)
validates: :cat_id, :start_date, :end_date, :status, presence: true
belongs_to :cat,
foreign_key: :cat_id,
class_name: :Cat
end
|
# encoding: utf-8
module Antelope
module Ace
class Scanner
# Scans the third part. Everything after the content
# boundry is copied directly into the output.
module Third
# Scans the third part. It should start with a content
# boundry; raises an error if it does not. It th... |
class CreateAttributes < ActiveRecord::Migration
def self.up
create_table :attributes do |t|
t.string :name, :limit => 20, :null => false
t.timestamps
end
end
end
|
#!/usr/bin/env ruby
require "date"
require "fileutils"
require File.expand_path("../../storm_data/storm_events.rb", __FILE__)
require File.expand_path("../forecast.rb", __FILE__)
FROM_ARCHIVE = ARGV.include?("--from-archive")
DRY_RUN = ARGV.include?("--dry-run")
DELETE_UNNEEDED = ARGV.include?("--delete-un... |
class MonstersController < ApiController
before_action :require_login, except: [:index, :show]
def index
monsters=Monster.all
render json:{monsters: monsters}
end
def show
monster=Monster.find(params[:id])
monster_user=monster.user
render json:{monster: monster}
end
def create
monster=Monster.new(m... |
class ServicesController < ApplicationController
def index
@title = "Services"
@services = Service.all
end
end
|
require 'account'
require 'date'
RSpec.describe Account do
subject(:account) { described_class.new } # account = Account.new
# date = DateFormat.new
let(:amt) { 1000 }
let(:date) { '09/09/2020' }
let(:type) { ' ' }
# describe '#date' do # hashtag means you're testing a method
# it 'shows the date' do
... |
class Vanagon
module Utilities
module ExtraFilesSigner
class << self
def commands(project, mktemp, source_dir) # rubocop:disable Metrics/AbcSize
tempdir = nil
commands = []
# Skip signing extra files if logging into the signing_host fails
# This enables things... |
$: << File.expand_path('../lib', __FILE__)
require 'rack-emstream'
class Sender
def initialize
@times = 100
@data = "data"
end
def each
@times.times { |i|
yield @data
}
end
def length
@times * @data.length
end
end
require 'logger'
use Rack::EMStream
run lambda { |env|
sender... |
require 'spec_helper'
describe ExamRoom::Practice::Exam do
before :each do
setup_for_models
end
describe "scopes" do
it "completed" do
practice_exam = TestSupport::ExamRoom.generate_practice_sba_exam!
ExamRoom::Practice::Exam.completed.count.should == 0
practice_exam... |
module SessionsHelper
#Logs in the given user
def log_in(user)
session[:user_id] = user.id # creates a temp cookie and encrypt user.id
end
#return the current login user
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
#Return true if user is logged in, else false
d... |
class PositionsController < ApplicationController
before_filter :authenticate_user!
before_action :set_position, only: [:show, :edit, :update, :destroy]
after_action :verify_authorized, :except => [:index, :new]
before_action :set_authorize_check, :except => [:index, :new] # This always follows the verify_autho... |
describe Limbo::Rails::Request do
describe "#url" do
context "URL with a standard port" do
it "returns a formatted URL without port" do
rails_request = Limbo::Rails::Request.new(request(port: 80))
rails_request.url.should == "http://example.com/blog"
end
end
context "URL with ... |
class JavascriptSweeper < ActionController::Caching::Sweeper
observe Javascript
def after_update(asset)
expire_cache_for asset if asset.type == 'Javascript'
end
def after_destroy(asset)
expire_cache_for asset if asset.type == 'Javascript'
end
private
def expire_cache_for(record)
... |
#
# Be sure to run `pod lib lint MideaSmartCommon.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'Mid... |
require 'matrix'
require_relative 'print'
# @param [Matrix] _a
# @param [Array] _b
def gauss(_a, _b)
a, b = _a.dup, _b.dup
size = a.row_size
(0...size - 1).each do |i|
(i + 1...size).each do |j|
ratio = a[j, i] / a[i, i]
b[j] -= ratio * b[i]
(0...size).each do |k|
a[j, k] -= ratio ... |
require "pathname"
require "fileutils"
module Snapit
class Storage
attr_reader :path
def initialize(root_path)
@path = root_path.join("snapit_captures")
FileUtils.mkdir_p(path) unless Dir.exists?(path)
end
def set_script_name!(name)
@script_name = name
@script_name = @script... |
TeamUserType = GraphqlCrudOperations.define_default_type do
name 'TeamUser'
description 'TeamUser type'
interfaces [NodeIdentification.interface]
field :dbid, types.Int
field :user_id, types.Int
field :team_id, types.Int
field :status, types.String
field :role, types.String
field :permissions, types... |
class DefectsController < ApplicationController
before_filter :set_project
before_action :set_defect, only: [:show, :edit, :update, :destroy]
before_action :set_breadcrumbs
# GET /defects
# GET /defects.json
def index
@defects = @project.defects
@defect = Defect.new
end
# GET /defects/1
#... |
# this is a sample model for testing purpose
class Event #:nodoc:
include Mongoid::Document
field :name, type: String
field :date, type: Date
field :published, type: Mongoid::Boolean, default: false
default_scope ->{ where(published: true) }
end
|
Convention over Configuration(CoC)
Less code to write
Some code Rails will automatically generate
Often, there is no need to code
Database Abstraction Layer
No need to deal with low-level DB details
No need for SQL
Important to understand the SQL generated!
**ORM: Object-Relational Mapping: mapping db to Ru... |
# frozen_string_literal: true
require 'spec_helper'
describe ImageBatchesDownloadService do
let(:target_folder) { Dir.mktmpdir }
let(:fixtures_path) { "#{File.dirname(__FILE__)}/fixtures/" }
let(:images) do
{
'airplane.png' => 'https://homepages.cae.wisc.edu/~ece533/images/airplane.png',
'arctic... |
class AddUserIdToTsubuyakies < ActiveRecord::Migration
def change
add_column :tsubuyakies, :user_id, :integer
end
end
|
def vendor_build_env
# Each of the following environment variables should be set,
# preferably by an automated tool like Qt::Commander::Creator::Toolchain#env
[
'ANDROID_NDK_ROOT', # eg. "/home/user/android/android-ndk-r9d"
'TOOLCHAIN_PATH', # eg. "/home/user/android/android-ndk-r9d/toolchains/arm-linu... |
# -*- coding : utf-8 -*-
module Mushikago
module Hanamgri
class SaveDictionaryRequest < Mushikago::Http::PutRequest
def path; "/1/hanamgri/dictionary" end
request_parameter :domain_name
request_parameter :description
def initialize domain_name, options={}
super(options)
se... |
describe NOAA do
it { should respond_to :forecast }
it { should respond_to :current_conditions }
it { should respond_to :current_conditions_at_station }
end
|
class CreateConsultantSkills < ActiveRecord::Migration
def change
create_table :consultant_skills do |t|
t.references :consultant, index: true, null: false
t.references :skill, index: true, null: false
t.timestamps
end
end
end
|
class CreateSales < ActiveRecord::Migration
def change
create_table :sales do |t|
t.string :customer_name
t.date :delvery_note_date
t.integer :delvery_note_number
t.date :tax_invoice_date
t.integer :tax_invoice_number
t.string :particuars
t.string :quantity
t.string... |
# frozen_string_literal: true
class JobsClientSelectComponent < ViewComponent::Base
def initialize(selected: nil)
clients = Client.all
@clients_for_select = clients.map {|c| [c.name, c.id]}
@clients_for_select.push(['Add new...', -1])
@selected = selected&.id
end
end
|
class RepoWorker
include Sidekiq::Worker
def perform
base_url = "https://atom.io"
page_path = "/packages/list"
page_url = base_url + page_path
# FIXME: Maybe timeout
home = Nokogiri::HTML(Typhoeus.get(page_url).body)
page_total = home.css('.pagination a:not(.next_page)').last.content
l... |
module Light
module Decorator
module Concerns
module Associations
module CollectionProxy
extend ActiveSupport::Concern
# Decorate ActiveRecord::Model associations
#
# @param [Hash] options (optional)
# @return [ActiveRecord::Associations::Collection... |
module Hayaku::WebSockets
class ListenerManager
def initialize
@listeners = []
end # initialize
def register(listener)
if listener.is_a?(Hayaku::WebSockets::Listener)
@listeners << listener
end
end
def for(connection, event)
connection = connection.to_s
... |
class AddSecretTokenToGsParameter < ActiveRecord::Migration
def up
require 'securerandom'
GsParameter.create(:name => 'SECRET_TOKEN', :section => 'Cookies', :value => SecureRandom.hex(64), :class_type => 'String')
end
def down
GsParameter.where(:name => 'SECRET_TOKEN').destroy_all
end
end
|
class UsersController < ApplicationController
before_action :authenticate_user!
#before_action :require_admin
def index
@users=User.all
end
def show
end
def new
@user=User.new
end
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html ... |
json.array!(@words) do |word|
json.extract! word, :id, :name, :definition, :example
json.url word_url(word, format: :json)
end
|
#!/usr/bin/env jruby
require 'jrubyfx'
class LineChart < JRubyFX::Application
def start(stage)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
values = [[23, 14, 15, 24, 34, 36, 22, 45, 43, 17, 29, 25],
[33, 34, 25, 44, 39, 16, 55, 54,... |
# -*- mode:ruby; coding:utf-8 -*-
require 'www/enbujyo/helper'
module WWW
class Enbujyo
class Movie
include WWW::Enbujyo::Utils
STATES = [:none, :accepted, :encoding, :completed, :downloaded, :unavailable]
RESULT = [:win, :draw, :lose]
# needed
attr_reader :title, :date, :result, :... |
class JoinTableBoxContract < ApplicationRecord
belongs_to :box_simulation
belongs_to :box_contract
end
|
class CategoriesController < ApplicationController
before_action :fetch_common_data
def show
@category = Category.find params[:id]
@products = @category.products.onshelf.page(params[:page] || 1).per(params[:per_page] || 12).order(id: "desc").includes(:main_picture)
end
end
|
class AddCreateTimeToArticles < ActiveRecord::Migration
def change
add_column :articles, :create_time, :date, :null => false, :default => DateTime.now
end
end
|
require "rails_helper"
RSpec.describe DayHelper, type: :helper do
describe "#doy_to_date" do
it "turns year and day to a date" do
expect(doy_to_date(2018, 2)).to eq(Date.new(2018, 1, 2))
end
it "respects strings as input as well" do
expect(doy_to_date("2019", "5")).to eq(Date.new(2019, 1, 5)... |
class AgendasController < ApplicationController
before_action :find_agenda, except: [:index, :new, :create]
def index
@agendas = current_user.agendas.all
end
def new
@agenda = current_user.agendas.build
end
def create
@agenda = current_user.agendas.build(agenda_params)
if @agenda.save
... |
# @param {Integer[]} nums
# @return {Integer}
def num_identical_pairs(nums)
good_pairs_count = 0
0.upto(nums.length - 1) do |i|
1.upto(nums.length - 1) do |j|
if nums[i] == nums[j] && i < j
good_pairs_count += 1
end
end
end
return good_pairs_count
end
|
class Cellnum
attr_accessor :owner
attr_reader :code
@@Size=48
def initialize(x)
if x.is_a? Cellnum
@val=x.val
@code=x.code
else
@code=nil
@val=Cellnum.to_bin_range(x.to_i,@@Size);
end
end
def val
@val
end
def val=(v)
@val=v
@code=nil
end
def +(x)
Cellnu... |
require 'rspec'
require 'pry'
require 'colorize'
puts "\nBANKING CODE CHALLENGE".yellow
puts "XXXXXXXXXXXXXXXXXXXXXX".yellow
puts "\nPART 1".magenta
puts "\nCreate the models and their relationships to accurately reflect banks, accounts and transfers.".green
bank1 = BankingCodeChallenge::Bank.new("Bank1")
account_1... |
#! /usr/bin/env ruby
#
# script used to start ocean visualization environment
# loads the flat_fish.world
#
require 'vizkit'
require 'rock/bundle'
require 'rock/gazebo'
require 'sdf'
#
# add model paths to GAZEBO_MODEL_PATH variable
#
ENV['GAZEBO_MODEL_PATH'] = "#{ENV['GAZEBO_MODEL_PATH']}:#{ENV['AUTOPROJ_CURRENT_ROOT'... |
require_relative 'kii_api'
require_relative 'kii_object'
class KiiBucket
include KiiAPI
include KiiObjectPersistance
def initialize name, context, path
@name = name
@context = context
@path = path
end
def new_object data
KiiObject.new data, @context, "#{@path}/buckets/#{@name}/objects"... |
module Kademy
module Locale
LOCALE_SUBDOMAINS = {
"en" => 'www',
"es" => 'es-es',
"de" => 'de',
"fr" => 'fr',
"pt" => 'pt'
}
def self.get_locale_subdomain(locale = nil)
check(locale)
LOCALE_SUBDOMAINS[locale]
end
def self.check(locale=nil)
raise ... |
RSpec.describe Dashing::DashboardsController do
before do
@routes = Dashing::Engine.routes
end
describe 'GET "index"' do
def action
get :index
end
it 'responds success' do
action
expect(response).to be_success
end
end
describe 'GET "show"' do
def action(params ... |
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "celly/version"
Gem::Specification.new do |s|
s.name = "celly"
s.version = Celly::VERSION
s.authors = ["Jared Pace"]
s.email = ["jared@codeword.io"]
s.homepage = ""
s.summary = %q{Sends a reimbursemen... |
class AddSeveralAttrToEpisodes < ActiveRecord::Migration[5.0]
def change
change_table :episodes do |t|
t.boolean "favorite"
t.boolean "seen"
t.integer "rating"
end
change_column_default :episodes, :favorite, false
change_column_default :episodes, :seen, false
change_column_default :episo... |
# frozen_string_literal: true
module HelpScout
class API
class Client
attr_reader :authorize
def initialize(authorize: true)
@authorize = authorize
end
def connection
@_connection ||= build_connection.tap do |conn|
if authorize?
HelpScout::API::Acce... |
class CreateStatuses < ActiveRecord::Migration
def change
create_table :statuses do |t|
t.integer :user_id
t.string :title
t.text :content
t.timestamps null: false
end
end
end
|
module MTMD
module FamilyCookBook
class Pagination
PAGE_SIZE = 20
PAGE_NUMBER = 1
attr_reader :page_size,
:page_number
attr_accessor :errors_array,
:total
def initialize(options = {})
options = options.symbolize_keys
... |
# ### `Recipe`
# Build the following methods on the Recipe class
class Recipe
@@all = []
def initialize(name)
@name = name
@@all << self
end
# - `Recipe.all`
# should return all of the recipe instances
def self.all
@@all
end
# - `Recipe.most_popular`
# should return th... |
FactoryGirl.define do
sequence(:random_string) {|n| SecureRandom.hex}
sequence(:user_email) {|n| "somebody#{n}@test.com"}
factory :user do
email {generate(:user_email)}
password {generate(:random_string)}
factory :admin do
admin true
end
factory :provider_admin do
association :p... |
Rails.application.routes.draw do
get 'listings/index'
get 'listings/new'
get 'listings/show'
get 'listings/edit'
get 'categories/new'
get 'categories/show'
devise_for :users
resources :listings
root'listings#index'
# For details on the DSL available within this file, see http://guides.rubyonr... |
require File.dirname(__FILE__) + '/../../test_helper'
class UserRoutingTest < ActionController::TestCase
tests UserController
test 'route to :show' do
assert_routing '/user', { :controller => 'user', :action => 'show' }
end
test 'route to :new' do
assert_routing '/user/new', { :controller => 'user', ... |
module Peek
module Views
class AltRoutes < View
attr_reader :name
# A view that allows for quick toggling of alternative routes.
#
# name - Text that will be displayed in the peek bar. The name
# of the feature or pages that will be toggled.
#
# Returns Peek::Views... |
require 'spec_helper'
describe FacebookDialog::OptionSerialization do
subject do
FacebookDialog::OptionSerialization.new({
response_type: [:code, :token],
scope: [:offline_access, :email]
})
end
it "breaks an array of response types into a comma delimited list" do
subject.serialized_hash[... |
require 'ci/common'
def mysql_version
ENV['FLAVOR_VERSION'] || 'latest'
end
def mysql_flavor
ENV['MYSQL_FLAVOR'] || 'mysql'
end
def mysql_repo
if mysql_flavor == 'mysql'
if mysql_version == '5.5'
'jfullaondo/mysql-replication'
else
'bergerx/mysql-replication'
end
elsif mysql_flavor ==... |
module FunnelsHelper
def funnel_data(params = {})
# format input
start_date = Date.today.beginning_of_week
end_date = Date.today.end_of_week
if params.has_key? :start_date
start_date = params[:start_date].to_date.beginning_of_week
end
if params.has_key? :end_date
end_date = par... |
# frozen_string_literal: true
# Indexes resources loaded into Fedora from CITI.
class CitiIndexer < ActiveFedora::IndexingService
def generate_solr_document
super.tap do |solr_doc|
solr_doc["read_access_group_ssim"] = ["group", "registered"]
solr_doc[Solrizer.solr_name("aic_type", :facetable)] = objec... |
class Api::V1::TweetsController < ApplicationController
module TwitterAuthentication
def client
Twitter::REST::Client.new do |config|
config.consumer_key = ENV.fetch('TWITTER_CONSUMER_KEY')
config.consumer_secret = ENV.fetch('TWITTER_CONSUMER_SECRET')
config.access_token ... |
class TagTimeRange < ActiveRecord::Base
# Attributes
# ----------
belongs_to :time_range
belongs_to :tag
end
|
class ChangeOrderCloumnName < ActiveRecord::Migration[5.1]
def change
rename_column :orders, :status, :order_status
end
end
|
# frozen_string_literal: true
module TimeClusterHelper
STATUS_INDICATORS = {bad: %w([* *]), questionable: %w([ ])}.with_indifferent_access
def time_cluster_display_data(cluster, display_style, options = {})
with_status = options[:with_status]
formatted_times = time_cluster_data(cluster, display_style).map... |
desc 'Enables default actions for all existing projects'
task enable_default_actions: [:environment] do
Project.all.each do |project|
if project.actions.blank?
project.actions = GithubAction::DEFAULT_ACTIONS
project.save!
end
end
end
|
##
#* Order database model
#* generated by scaffold
class Order < ActiveRecord::Base
attr_accessible :address, :email, :name, :pay_type
##
# the following relations are described in project.rdoc
has_many :line_items , :dependent => :destroy
##
# the two common payment types
PAYMENT_TYPES = [ "Direct pay a... |
# $Id$
require 'attr_encrypted'
class BackupSource < ActiveRecord::Base
belongs_to :member, :foreign_key => 'user_id'
belongs_to :backup_site
has_many :backup_source_days
has_many :backup_photo_albums
has_many :backup_source_jobs
@@max_consecutive_failed_backups = 25 # Should be about 1 day's worth
@... |
class RenameOnlineToState < ActiveRecord::Migration
class Instance < ActiveRecord::Base; end
def up
add_column :gpdb_instances, :state, :string, :default => 'online'
GpdbInstance.reset_column_information
GpdbInstance.update_all(:state => 'online')
GpdbInstance.where("online = false").update_all(:s... |
namespace :count_models do
desc 'Count all of the Models.'
task :models => :environment do
puts ' '
puts 'Current Movies = ' + Movie.count.to_s
puts ' '
puts 'Current Theaters = ' + Theater.count.to_s
puts ' '
puts 'Current Users = ' + User.count.to_s
puts ' '
puts 'Current Vi... |
require_relative 'spec_helper'
require_relative '../lib/friend_entries_fetcher'
describe FriendEntriesFetcher do
let(:lj_driver) { double(:lj_driver) }
let(:rss_items_extractor) { double(:rss_items_extractor) }
let(:friend_entries_fetcher) { FriendEntriesFetcher.new lj_driver, rss_items_extractor }
it 'fetche... |
class Microinjection < ActiveRecord::Base
#Note that Andreas should be able to create one of these records with almost nothing for a clone
validates_presence_of :status, :clone_name, :mgi_accession_id
#WHEN an id is stamped on, it should be unique across all records
validates_uniqueness_of :production_cen... |
class Post < ActiveRecord::Base
acts_as_taggable_on :post_tags
has_attached_file :image,
:storage => :s3,
:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",
:path => ":rails_root/public/ckeditor_assets/pictures/:id/:style_:basename.:extension",
:styles => { :medium => "300x300>",:small=> "200x20... |
def is_valid(s)
hash = {
'(' => ')',
'{' => '}',
'[' => ']'
}
arr = Array.new
(0...s.size).each do |index|
if arr.empty? or hash[arr.last] != s[index]
arr.push(s[index])
else
arr.pop
end
end
return arr.empty?
end
puts is_valid "()"
puts is_valid "()[]{}"
puts is_valid "(]"
puts is_valid "([)]... |
class ApplicationController < ActionController::API
def encode_token(payload)
JWT.encode(payload, hmac_secret, 'HS256')
end
def user_payload(user)
{user_id: user.id}
end
def hmac_secret
ENV['JWT_SECRET_KEY']
end
def token
request.headers['Authorization']
... |
#!/usr/local/bin/ruby -w
# This program demonstrates a bug in the Sqlite DBD: DBH#do should
# return the row processed count, but it returns nil
# When run with dbi-0.0.23 this program gives:
# Oops! count1=nil
require 'dbi'
File.delete('foo') if FileTest.exists?('foo')
db = DBI.connect('dbi:sqlite:foo')
db['AutoCo... |
class DrugStock < ApplicationRecord
belongs_to :facility, optional: true
belongs_to :region
belongs_to :user
belongs_to :protocol_drug
validates :in_stock, numericality: true, allow_nil: true
validates :received, numericality: true, allow_nil: true
validates :for_end_of_month, presence: true
scope :wi... |
require 'rails_helper'
RSpec.describe "locales/edit", type: :view do
before(:each) do
@locale = assign(:locale, Locale.create!(
:name => "MyString",
:municipality => nil
))
end
it "renders the edit locale form" do
render
assert_select "form[action=?][method=?]", locale_path(@locale)... |
module API
class Entrance < Grape::API
# Api logger
def self.logger
Logger.new("#{Rails.root}/log/api.log")
end
# 404
rescue_from ActiveRecord::RecordNotFound do
rack_response({message: '404 Not found'}.to_json, 404)
end
# 400
rescue_from Grape::Exceptions::ValidationErro... |
class PdfStatement < Prawn::Document
# { "category"=>"M",
# "customer"=>{ "birth_date"=>"1953-11-27",
# "given_names"=>"Krzysztof",
# "id"=>"74975", "name"=>"Ziętara"},
# "date_of_issue"=>"2018-07-13",
# "division"=>{ "english_name"=>"VHF radiotelephone operator's... |
require 'rails_helper'
feature 'message board only shows current day' do
context 'as an authorized user' do
let(:user) { FactoryGirl.create(:user) }
before :each do
sign_in_as user
end
scenario 'I just see messages for today' do
family = FactoryGirl.create(:family_membership, user: user)... |
class MoviesController < ApplicationController
def show # show more details about...
id = params[:id] || session[:id] # retrieve movie ID from URI route
@movie = Movie.find(id) # look up movie by unique ID
# will render app/views/movies/show.<extension> by default
end
def index
@movies = Movie.a... |
class Card
FACE_CARDS_RANKED = [
"2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"
]
def initialize(card_str)
raise EmptyCardError if card_str.nil? || card_str.empty?
@card_str = card_str
end
def face
@card_str[0]
end
def suit
@card_str[1]
end
class EmptyCardErro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.