text stringlengths 10 2.61M |
|---|
module LinkHelper
include URI
include Rack::Utils
def self.validate(link)
if link.class != String
return false
end
if link !~ /^(http|https):\/\//
link = 'http://' + link
end
if link !~ $URI_REGEXP
return false
end
return link
end
def self.parse(uri)
return ... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'thor'
require 'yaml'
require 'midea_air_condition'
# Command Line Interface
class MideaCLI < Thor
CONFIG_PATH = File.expand_path('~/.midea/config')
desc 'configure', 'Configure client'
def configure
credentials = {}
credentials['email'] = ask('... |
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "https://partners.thinmanager.com"
SitemapGenerator::Sitemap.create do
# Put links creation logic here.
#
# The root path '/' and sitemap index file are added automatically for you.
# Links are added to the Sitemap in the order they ... |
require 'slackbotsy'
require 'active_support'
require 'active_support/hash_with_indifferent_access'
require 'sinatra'
require 'newrelic_rpm'
require 'json'
Dir.glob(File.join(File.dirname(__FILE__), 'services', '*.rb')).each do |service|
require service
end
config = {
'team' => ENV['SLACK_TEAM'],
'cha... |
require 'require_relative' if RUBY_VERSION[0,3] == '1.8'
require_relative 'acceptance_helper'
describe "update" do
include AcceptanceHelper
it "goes to one update's page" do
u = Fabricate(:update)
visit "/updates/#{u.id}"
within ".update .update-text" do
assert has_content?(u.text)
end
en... |
require "spec_helper"
describe AuxFilesController do
describe "routing" do
it "routes to #show" do
get("/aux_files/1").should route_to("aux_files#show", :id => "1")
end
it "routes to #destroy" do
delete("/aux_files/1").should route_to("aux_files#destroy", :id => "1")
end
end
end
|
class CommentsController < ApplicationController
def new
@comment = Comment.new
end
def create
@comment = Comment.new(comment_params)
@comment.user = current_user
if @comment.save
flash[:notice] = "Created comment"
redirect_to article_path(@comment.base_article)
else
flas... |
require 'oystercard'
describe Oystercard do
describe '#balance' do
it 'should show 0 balance' do
expect(subject.balance).to eq(0)
end
it 'should deduct by 6 if you touch in twice' do
subject.top_up(20)
expect{ 2.times{subject.touch_in(liverpool_street)} }.to change{ subject.balance}.b... |
class CreateTrips < ActiveRecord::Migration[5.1]
def change
create_table :trips do |t|
t.string :destination
t.string :date_of_dep
t.string :date_of_arr
t.string :start_city
t.string :end_city
t.string :details
t.timestamps
end
end
end
|
class ListingsPolicy < ApplicationPolicy
attr_reader :listing
def initialize(user, listing)
@user = user
@listing = listing
end
def create?
@user.admin?
end
end
|
# Summarize_app
text = %q{
Ruby is a great progrramming language. It is object oriented
and has many groovy features. Some people don't like it but that's
not our problem! It's easy to learn. It's great. To learn more about Ruby,
visit the official ruby website today.
}
sentences = text.gsub(/\s... |
require 'csv'
require_relative 'book_in_stock'
class CsvReader
def initialize
@book_in_stock = []
end
def read_in_csv_data(csv_file_name)
CSV.foreach(csv_file_name, headers: true) do |row|
@book_in_stock << BookInStock.new(row['ISBN'], row['Price'])
end
end
def total_value_in_stock
t... |
namespace :misc do
namespace :generator do
desc "Create Random Info for User Accounts"
task :accounts => :environment do
include Markhov
maxusers = ENV["users"].to_i || 10
corpus = "#{RAILS_ROOT}/config/lorem-small.txt"
puts "Creating #{maxusers} Accounts"
puts " - (Loading ... |
module CDI
class BaseService
include ServiceConcerns::BaseConcern
attr_reader :options, :response_status, :errors
CALLBACKS = [
:after_initialize,
:before_error,
:after_error,
:after_success,
:before_success
]
ERROR_RESPONSE_METHODS = {
:bad_request_error ... |
1.upto(5) do |n|
WebMock
.stub_request(
:get,
'https://api-ssl.bitly.com/v3/shorten?access_token=valid_token' \
"&longUrl=http://example.org/200/#{n}"
)
.to_return(
status: 200,
body: %({
"status_code": 200,
"status_txt": "OK",
"data": {
"lo... |
require 'error_codes'
module Api
module V1
class BaseApiController < ApplicationController
include BaseDoc
before_filter :remove_empty_params_and_headers
before_filter :set_custom_response_headers
before_filter :authenticate_from_token!
respond_to :json
def about
re... |
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
helper_method :pretty_date, :pretty_pace, :current_user
before_filter :ensure_logged_in
private
def current_us... |
class VideosController < ApplicationController
before_action :require_user
before_action :is_admin?, only: [:index, :new, :create, :edit, :update, :destroy]
before_action :set_video, only: [:edit, :update, :show]
def index
@videos = Video.all
end
def new
@video = Video.new
end
def crea... |
class ProfessorsPublications < ActiveRecord::Migration
def change
create_table :professors_publications, :id => false do |t|
t.references :professor
t.references :publication
end
add_index :professors_publications, [:professor_id, :publication_id]
end
end
|
class Item < Collection
include ActiveModel::Validations
COLLECTION = Cache.get_collection(collection_key.pluralize)
ACCESSORS = [
:name, :sanitizedDescription
].freeze
ACCESSORS.each do |accessor|
attr_accessor accessor
end
validates :name, presence: true, inclusion: COLLECTION.values
def co... |
class MultiplesSolver
def self.solve(num)
1.upto(num - 1).inject(0) do |total, n|
if n % 3 == 0 || n % 5 == 0
total + n
else
total
end
end
end
end
|
class RegistrationsController < ApplicationController
def create
if reg_params[:phone].present? or reg_params[:email].present?
@reg = Registration.new(reg_params)
if @reg.save
flash[:message] = 'Отправлено успешно'
end
else
flash[:message] = 'Заполните одно из полей'
end
... |
# archlib.rb
# Indicates the lib folder name for redhat based systems
Facter.add(:archlib) do
setcode do
begin
Facter.loadfacts()
arch = Facter.value('architecture')
osfamily = Facter.value('osfamily')
if arch =~ /^x86_64/ && osfamily == 'RedHat'
... |
# frozen_string_literal: true
class Category < ApplicationRecord
has_many :incidents
belongs_to :parent, foreign_key: 'category_id', class_name: 'Category', optional: true
has_many :children, class_name: 'Category', dependent: :destroy
belongs_to :sla
belongs_to :group, optional: true
end
|
class User < ActiveRecord::Base
has_many :active_codes, :dependent => :destroy
has_many :entries, :dependent => :destroy
before_save :rehash_password
def self.authenticate(username, password)
User.where({
:username => username.to_s.downcase,
:password => hash_password(username, password),
... |
# Write a method that takes an Array as an argument, and reverses its elements in place; that is, mutate the Array passed into this method. The return value should be the same Array object.
=begin
approach:
- idea:
- swap the element at 0 and element at (list.size - 1)
- then swap element at 1 and element at (li... |
class ProducersController < ApplicationController
before_action :redirect_if_not_logged_in
before_action :set_producer, only: [:show, :edit, :update, :destroy]
def index
@producers = Producer.all
end
def new
@producer = Producer.new
end
def create
producer = P... |
FactoryBot.define do
factory :package do
shipping_type { 1 }
h { 23 }
w { 12 }
l { 23 }
weight { 390 }
batch
profile
end
end
|
class Reindeer
attr_reader :location
attr_accessor :name
def initialize(name)
@name = name
@location = "the North Pole"
end
def take_off(altitude)
puts "#{@name} took off."
puts "#{@name} ascended to #{altitude} feet."
end
def land(location)
puts "#{@name} landed safely in #{locatio... |
# frozen_string_literal: true
Rails.application.routes.draw do
get 'vue_application/index'
root 'vue_application#index'
namespace :api do
namespace :v1 do
mount_devise_token_auth_for 'User', at: 'auth'
resources :incidents
resources :users
resources :categories
resources :grou... |
class QuizAnswersController < ApplicationController
before_action :set_quiz_answer, only: %i[ show edit update destroy ]
# GET /quiz_answers or /quiz_answers.json
def index
@quiz_answers = QuizAnswer.all
end
# GET /quiz_answers/1 or /quiz_answers/1.json
def show
end
# GET /quiz_answers/new
def ... |
require 'test_helper'
class SkillRelationsControllerTest < ActionController::TestCase
setup do
@skill_relation = skill_relations(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:skill_relations)
end
test "should get new" do
get :new
as... |
class Rehearsal < ApplicationRecord
belongs_to :event
has_many :attendances, dependent: :destroy
has_many :students, through: :attendances
has_many :comments, dependent: :destroy
delegate :user, :to => :event, :allow_nil => true
validates :venue, presence: true
def students_attending
self.att... |
class Account < ActiveRecord::Base
has_many :journals
has_many :account_line_items
has_many :items
default_scope {where(:deleted => nil)}
end
|
class List < ActiveRecord::Base
has_many :todo, dependent: :delete_all
belongs_to :user
validates :title, :user_id , presence: true
validates_length_of :title, in: 3..40
validates_length_of :description, maximum: 140, allow_blank: true
end
|
# In the input_students method the cohort value is hard-coded.
# How can you ask for both the name and the cohort?
# What if one of the values is empty?
# Can you supply a default value? The input will be given to you as a string?
# How will you convert it to a symbol? What if the user makes a typo?
def input_st... |
class CreateBandMemberships < ActiveRecord::Migration
def self.up
create_table :band_memberships do |t|
t.integer :artist_id
t.integer :band_id
t.date :joined
t.date :left
t.integer :created_by
t.integer :updated_by
t.integer :status
t.timestamps
end
end
d... |
Rails.application.routes.draw do
resources :ballots, only: [:create]
resources :results, only: [:index]
resources :topics, only: [:create, :index, :show, :destroy]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get '/topics', to: 'home#topics'
get '/', ... |
class Api::V1::ProductsController < ApplicationController
def index
products = Product.all
products = products.where('name ilike ?', "%#{params[:q]}%") unless params[:q]&.empty?
products = products.where(retailer_id: params[:retailer_id]) if params[:retailer_id]
render_all(datas: products)
end
de... |
require 'optparse'
require 'RMagick'
option = {}
OptionParser.new do |opt|
opt.on('-s', '--src=VALUE', 'Source file path') {|v| option[:src] = v}
opt.on('-d', '--dst=VALUE', 'Destination file path') {|v| option[:dst] = v}
opt.on('-f', '--flip=VALUE', 'Flip u | v | uv | vu') {|v| option[:flip] = v}
opt.... |
#!/usr/bin/env ruby
puts (1..999999).collect { |n| Enumerator.new { |c| a=n; loop { c<<a; break if a==1 ; a.even? ? a=a/2 : a=3*a+1 } }.collect { |c| c} }.max_by { |c| c.count }.first
|
class Search < ActiveRecord::Base
belongs_to :phrase
validates :input, presence: true
scope :session, ->(session_key) { where(session_key: session_key) }
scope :delete_all_by, ->(session_key, ids) { delete_all(session_key: session_key, id: ids) }
scope :include_synonyms, -> { includes(phrase: [:synonym_phra... |
class Admin::ProductsController < Admin::AdminController
before_action :set_product, only: [:edit, :show, :destroy, :update]
def index
@products = Product.all
end
def new
@product = Product.new
end
def update
if Product.update(product_params)
redirect_to admin_products_path, :flash=>{ ... |
require 'yaml'
require 'iconv'
module ID3V24
class Frame
attr_reader :type
attr_accessor :value
def self.create_frame(type, value)
klass = find_class(type)
if klass
klass.default(value)
else
# all the 'T###' frames contain encoded text, all the
# 'W###' fra... |
class StaticPagesController < ApplicationController
def home
@images = Image.order(possition: :asc)
end
end
|
require 'rails_helper'
describe 'builds' do
before do
@project = create_project('repo/project1', 'secret', {sha:'last-sha', message: 'first commit'})
visit projects_path
end
describe 'builds page' do
before { visit builds_path }
context 'sha of last commit are displayed' do
it { expect(... |
class Deck
attr_accessor :cards
def initialize
@cards = []
fill_deck # self is the instance here.
end
# call sample from deck of cards + delete!
def self.all
@@all
end
def fill_deck # becomes a helper method
# saves 52 deck of cards
# create instance of deck and shovel in cards; ea... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VAGRANTFILE_API_VERSION = "2"
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'docker'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
config.vm.define 'database' do |db|
db.vm.provider "docker" do |d|
d.image="mysql:latest"
d.env = {
# :MYSQL_ROOT_PASSW... |
class AddStylesToFemales < ActiveRecord::Migration
def change
add_column :females, :style, :string
end
end
|
# frozen_string_literal: true
require 'spec_helper'
# rubocop:disable Metrics/BlockLength
RSpec.describe ArchUpdate::Pacman do
let(:child_status_mock) do
`:`.yield_self do
$CHILD_STATUS
end
end
let(:option_parser_mock) do
double('Option parser mock').tap do |opm|
allow(opm).to receive(... |
class Movimiento2
attr_accessor :fecha, :tipo, :secuencia, :numero, :concepto, :debito, :credito, :saldo
extend ActiveModel::Naming
include ActiveModel::Conversion
def persisted?
false
end
def get_concepto
if self.tipo == 2
'**Nota de Credito**'
else
self.concepto
end ... |
#-skip:
# // Picture Follow Character
# // By IceDragon
# // Instructions:
# // picture_follow(picture_id, character_id)
# // int picture_id
# // int character_id
# // -1 - Player
# // 0 - Current event
# // 1 - every other event
#-end:
$simport.r 'iei/picture/follow', '1.0.0', 'IEI Picture F... |
module ErrorMessageTranslation
ERROR_CODE_AND_MESSAGE = /.*(\d{3})\s\-\s(.*)\s\/\/.*/
FORBIDDEN_ERROR_CODE = '403'
def self.from_error_response(error)
matches = error.message.match(ERROR_CODE_AND_MESSAGE)
if matches.present? && matches.captures[0] == FORBIDDEN_ERROR_CODE
matches.captures[1]
en... |
class MatchSynchronizer < Synchronisable::Synchronizer
gateway MatchGateway
has_one :team, key: 'home_team_id'
has_one :team, key: 'away_team_id'
remote_id :match_id
mappings(
:gninnigeb => :beginning,
:home_team => :home_team_id,
:away_team => :away_team_id,
:rehtaew => :weather,
:ln... |
require 'test/tem_test_case.rb'
class TemMigrateTest < TemTestCase
def _migrate_test_secret
[0x31, 0x41, 0x59, 0x65, 0x35]
end
def _migrate_test_seclosure
Tem::Assembler.assemble { |s|
s.label :secret
s.ldbc :const => _migrate_test_secret.length
s.dupn :n => 1
s.outnew
s.... |
class HealthyController < ApplicationController
def index
@users = User.where(status: false)
end
end
|
module CDI
module V1
module PageStructure
class CyclePlanningPageSerializer < BaseSerializer
has_one :cycle_planning, serializer: ModelSerializer::CyclePlanningSerializer
has_many :questions_templates, serializer: ModelSerializer::QuestionTemplateSerializer
end
end
end
end |
=begin
Write another method that returns
true if the string passed as an
argument is a palindrome, false
otherwise. This time, however,
your method should be case-insensitive,
and it should ignore all non-alphanumeric
characters. If you wish, you may simplify
things by calling the palindrome? method
you wrote... |
class AnswersController < ApplicationController
before_filter :get_category
before_filter :get_question
before_filter :require_user, except: [:index, :show]
before_filter :require_admin_user, only: [:edit, :update, :destroy]
# GET /answers
# GET /answers.json
def index
@answers = Answer.all
res... |
class Admin::StudentsController < ApplicationController
before_filter :authorize_admin
layout "admin"
# GET /students
# GET /students.json
def index
@students = Student.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @students }
end
end
# G... |
class Notification
include PushapiHelper
attr_accessor :title, :description, :URL, :orinoco, :myignId, :deviceToken, :appId, :eventType, :payload, :noAlert
def initialize(app, options = {})
@appId = app.appId
@title = options[:title] if options[:title]
@description = options[... |
require 'spec_helper'
describe AlertHelper, type: :helper do
before do
@alert = AlertHelper::ALERTS.sample
@message = "#{@alert.to_s.capitalize} Will Robinson!"
end
describe "alerts?" do
it "return false when no alerts are set" do
expect(helper.alerts?).to be false
end
it "return... |
describe 'Fazer uma requisicao HTTParty' do
it 'Requisicao post usando HTTParty' do
@body = {
"token_account":"3f35bb4dc40f28b",
"customer":{
"contacts":[
{
"type_contact":"H",
"number_contact":"113322... |
Pod::Spec.new do |s|
s.name = 'MappIntelligence'
s.version = '5.0.0-beta4'
s.author = { 'Mapp Digital' => 'devgroup.mobile@webtrekk.com' }
s.homepage = 'https://mapp.com/mapp-cloud/analytics/app-analytics/'
s.license = { :type => 'MIT', :file => 'LICENSE.md' }
s.ios.deployment_target = '... |
class Parent
def death
if @health <= 0
@status = "Dead"
end
end
def reduce_health(value)
@health - value
end
def find_by_name(name)
self.all.detect {|e| e.name == name}
end
def find_or_create_by_name(name)
self.find_by_name(name) || self.create(name)
end
end |
#! /usr/bin/env ruby
STDOUT.sync = true
puts "-----> Checking for absolute values in PATHs"
if ENV["FORCE_ABSOLUTE_PATHS_BUILDPACK_BUILD_DIR"]
buildpack_build_dir = ENV["FORCE_ABSOLUTE_PATHS_BUILDPACK_BUILD_DIR"]
# If the build dir and runtime dir are the same, we don't need to run the check
buildpack_build_di... |
# encoding: utf-8
class Campaign < ActiveRecord::Base
attr_accessible :title, :content, :image, :begin_date, :over_date, :link
validates :title, :content,:image, :begin_date, :over_date, presence: true
mount_uploader :image, ::ImageUploader
#取最新活动.每次只有一个 返回的是数组对象
scope :latest_campaign, order('id desc').lim... |
# $Id: core_ext.rb 109 2007-04-07 15:29:03Z stefan $
# Created by Stefan Saasen.
# Copyright (c) 2006. All rights reserved.
module WDDX
module Core # :nodoc:
def to_wddx
WDDX.dump(self)
end
end
def xml_escape(s)
s.to_s.
gsub(/&/, "&").
gsub(/\"/, """).
gsub(/>/, "... |
# createInstance.rb
#
# Description: Create intance in OpenStack
#
require 'fog'
def log(level, msg, update_message=false)
$evm.log(level,"#{msg}")
$evm.root['service_template_provision_task'].message = msg if $evm.root['service_template_provision_task'] && update_message
end
def get_tenant
tenant_ems_id = $evm... |
#
#= User の バリデーションを管理するモジュール
#
module Concerns::User::Validation
extend ActiveSupport::Concern
# バリデーション
included do
validates :login,
presence: true,
uniqueness: true,
length: { in: 3..20 },
format: {with: /^[a-zA-Z0-9\_\-]+$/, multiline: true}
validates :password,
presen... |
require 'rails_helper'
describe TopicsController do
describe 'GET #new' do
it "renders the :new template" do
get :new
expect(response).to render_template :new
end
end
describe 'GET #edit' do
it "assigns the requested topic to @topic" do
topic = create(:topic)
get :edit, param... |
class StoriesController < ApplicationController
# 注意 expect預計 與 except除了 的差異
before_action :find_story, only: [:edit, :update, :destroy]
def index
@stories = current_user.stories.order(created_at: :desc)
end
def new
@story = current_user.stories.new
end
def create
@story = current_user.stor... |
class Kind < ActiveRecord::Base
has_many :puzzles, :order => 'name', :dependent => :destroy
validates_presence_of :name
validates_length_of :name, :maximum => 64
validates_length_of :short_name, :maximum => 10
validates_uniqueness_of :name, :short_name
def self.all
find :all, :include => :puzzles
en... |
#!/usr/bin/env ruby
# Cissa converts any Ruby class into a command-line program. The methods of the
# class are converted into commands that can be given to the executable at
# runtime, and which run the specified method. A help screen is automatically
# generated, and displayed if the user calls the program with -h o... |
class ProjectQuestion < ApplicationRecord
validates :project_id, presence: true
end
|
class Api::UsersController < ApplicationController
before_action :set_user, only: [:destroy, :show, :update, :attendances, :attending, :not_attending]
before_action :update_industry_user, only: [:update]
before_action :update_area_user, only: [:update]
skip_before_filter :authenticate_user!, only: [:new_email, ... |
module SwaggerLockController
extend ActiveSupport::Concern
included do
include Swagger::Blocks
swagger_path '/lock' do
operation :post do
key :description, 'Lock the account'
key :operationId, 'lockAccount'
key :produces, [
'application/json'
]
key :tags, ... |
# -*- coding: utf-8 -*-
=begin
Altere o programa de cálculo do fatorial, permitindo ao usuário calcular o fatorial
várias vezes e limitando o fatorial a números inteiros positivos e menores que 16.
=end
puts "============================================================="
print "Digite um numero (0 a 16) para calcul... |
class TrailLocation < ActiveRecord::Base
belongs_to :trail
belongs_to :location
has_many :quests
validates :location_id, :trail_id, :presence => true
validates :location_id, :uniqueness => { :scope => :trail_id }
end |
FactoryGirl.define do
factory :calendar_repetition do
name {Faker::Name.name}
end
end
|
class TweetsController < ApplicationController
include TwitterCredentialHelper
include ApplicationHelper
def index
end
def send_tweets
redirect_to root_path unless params['count']
@tweets = Tweet.limit(100).offset(params['count'].to_i)
render json: prepare(@tweets)
end
def stream
set_up... |
class Watch < ActiveRecord::Base
attr_accessible :episode_id, :user_id
belongs_to :episode
belongs_to :user
end
|
class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 3 }
validates :text, length: { minimum: 5 }, presence: true
end
|
class CreateTableProductUpdates < ActiveRecord::Migration[5.0]
def change
add_column :products, :admin_user_id, :integer
end
end
|
# frozen_string_literal: true
module MondialRelay
module ParcelShops
class Search
module Translations
PARAMS = {
country: :Pays,
parcel_shop_id: :NumPointRelais,
city: :Ville,
postal_code: :CP,
latitude: :Latitude,
longitude: :Longitude,
... |
class RemoveMobileIdentityFromUesrs < ActiveRecord::Migration[5.0]
def up
remove_column :users, :mobile_identity
end
def down
add_column :users, :mobile_identity, :string, :limit => 40
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Item, type: :model do
describe "商品一覧画面(/admins/items)のテスト" do
before do
visit admin_items_path
end
context '遷移先の確認' do
it '新規登録ボタンを押すと商品新規登録画面が表示される' do
click_link '新規登録'
expect(page).to eq '/admins/items/new... |
class PostsController < ApplicationController
before_filter :authorize, except: %i[index show show_content]
def index
@posts = authenticated? ? Post.all : Post.published.to_a
end
def show
@post = Post.find(params[:id])
if user_agent.mobile?
index
end
end
def show_content
@post =... |
class YearValueValidator < ActiveModel::Validator
def validate(record)
summary = 0
if record.year_value.present?
record.errors[:start_date] << 'Дата начала отсутствует' if !record.start_date.present?
record.errors[:finish_date] << 'Дата окончания отсутствует' if !record.finish_date.present?
... |
require 'pry'
require 'colorize'
require_relative 'player'
require_relative 'high_low'
require_relative 'slots'
require_relative 'wellsfargobank'
require_relative 'roulette'
require_relative 'dice'
require_relative 'punctuation_roulette'
require_relative 'deck'
# require_relative 'card'
# require_relative 'punctuation_... |
require 'rails_helper.rb'
feature 'Create users' do
scenario 'can create user' do
# visit '/'
visit '/'
# click on sign up link
click_link 'Sign up'
# fill in forms
fill_in 'Email', with: 'test@test.com'
fill_in 'Username', with: 'testusername'
fill_in 'Password', with: 'test'
fil... |
require 'rails_helper'
RSpec.describe Rating, type: :model do
subject { FactoryGirl.create :rating }
# ATTRS
it { should respond_to(:header) }
it { should respond_to(:review) }
it { should respond_to(:score) }
it { should respond_to(:image) }
it { should respond_to(:product_id) }
it { should respon... |
class IpAddress < ApplicationRecord
has_and_belongs_to_many :hostnames
end
|
require 'spec_helper'
describe Post do
context 'Demonstration of how datamapper works' do
it 'should be created and then retrieved from the db' do
expect(Post.count).to eq(0)
Post.create(body: 'whatsup', name: 'timmy')
expect(Post.count).to eq(1)
post = Post.first
expect(post.body... |
#!/usr/bin/env ruby
# Clone all the repos of an organization in github
# Assuming they have less than 1000 repos...
require 'rest-client'
require 'json'
unless ARGV.size == 4
puts "usage: clone-github-repos.rb username password hostname organization"
exit 1
end
begin
response = RestClient.get("https://#{ARG... |
class AddTurnOrderToGames < ActiveRecord::Migration
def change
add_column :games, :turn_orders, :string, index: true
remove_column :games, :current_turn_player_id
end
end
|
require 'test_helper'
class OrdersControllerTest < ActionController::TestCase
include Devise::TestHelpers
setup do
MerchantSidekick::default_gateway = :bogus_gateway
ActiveMerchant::Billing::Base.mode = :test
ActiveMerchant::Billing::CreditCard.require_verification_value = true
merchants = [merch... |
module Results
class Init
INFLATION_RATE = 1.0
RENT_GROWTH_RATE = 1.0
HOME_PRICE_GROWTH_RATE = 3.0
SAVINGS_RETURN_RATE = 1.0
MORTGAGE_RATE = 1.5
MORTGAGE_DURATION = 25
INSURANCE_RATE = 0.2
def self.call(payload)
new(payload).call
end
def initialize(payload)
@inco... |
require 'spec/spec_helper'
require 'maws/connection'
require 'maws/command'
require 'maws/commands/configure'
describe "configure command" do
before do
Instance.instance_eval {@@configurations_cache = nil}
end
it "defines template temporary output path" do
Configure::TEMPLATE_OUTPUT_DIR.should == File.... |
Cms.config do |config|
config.use_translations false
end
module JsonMethod
module InstanceMethods
def json(include_errors = false)
fields = self.try(:json_fields) || self.attribute_names
JsonHelper.resource_to_json(self, include_errors, fields)
end
end
end
ActiveRecord::Base.send(:include, J... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.