text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
class InstrumentForCart < ProductForCart
def purchasable_by?(acting_user, session_user)
# If an instrument is not purchasable, we always redirect. Hence, if super
# doesn't set an error path due to some specific error, we set the error path
# to the facility path.
super... |
class Account < ApplicationRecord
belongs_to :user
validates :user, presence: true
validates :amount, presence: true, :numericality => { :greater_than_or_equal_to => 0 }
validates :account_number, presence: true, uniqueness: true
has_many :transfers
has_many :deposits
has_many :withdrawals
has_many :b... |
require 'test/helper'
class CommentParser < Kss::Test
def setup
loc = 'test/fixtures/comments.txt'
@parsed_comments = Kss::CommentParser.new(loc).blocks
end
test "detects single-line comment syntax" do
assert Kss::CommentParser.single_line_comment?("// yuuuuup")
assert !Kss::CommentParser.singl... |
string_1 = "i am learning Ruby language."
string_2 = "why? Coz it's cool and I like it."
puts "1: Make string_1 capital case: " +string_1.split.map(&:capitalize).join(" ")
puts "2: Make string_1 lower case: " +string_1.downcase
puts "3: Change the string_1's each letter's case to the opposite case: " +string_1.swapcas... |
class CreateRestaurants < ActiveRecord::Migration[6.0]
def change
create_table :restaurants do |t|
t.string :name, null: false
t.text :description, null: false
t.string :dietary
t.string :category
t.integer :delivery_radius
t.float :average_rating
t.string :spotify_url
... |
command :info do |c|
c.syntax = 'rubychina info [topic]'
c.summary = 'Get information about a topic by its number'
c.description = ''
c.action do |args, options|
say_error "Missing topic id" and abort unless @number = (Integer(args.first) rescue nil)
session = get("/topics/#{@number}.json")
... |
module ShooterTest
class Shield
attr_reader :invincibility
extend SDCMeta::ClassProperty
self.define_class_property(:invincibility_time, default: 90.0)
def initialize
@invicibility = false
end
def update
if @invincibility then
@invincibility -= SDC.game.dt
if @invincibility <= 0 then
... |
class CreatePaymentRequest < ActiveRecord::Migration
def self.up
create_table :payment_requests do |t|
t.text :identification_token
t.text :transaction_parameters
t.integer :user_id
t.boolean :is_processed,:default => false
t.integer :school_id
t.timestamps
end
end
def ... |
include_recipe "nginx::default"
directory "/var/www" do
owner node[:user]
end
template "tristandunn" do
path "#{node[:nginx][:dir]}/sites-available/tristandunn"
owner node[:user]
if File.exist?("/etc/ssl/tristandunn.com.crt")
source "tristandunn.ssl.nginx"
else
source "tristandunn.nginx"
end
... |
require 'simplecov'
SimpleCov.start
require './lib/encoder'
require './lib/cypher'
describe Encoder do
before(:each) do
@message = 'hello world!'
@key = '02715'
@date = '040895'
@cypher = Cypher.new(@key, @date)
@encoder = Encoder.new(@cypher)
@big_message = "Hello world!
This is an example ... |
require 'rails_helper'
RSpec.describe Customer, type: :model do
context 'Customer' do
it 'Using attributes_for' do
attrs = attributes_for(:customer)
customer = create(:customer)
expect(customer.full_name).to start_with("Sr. ")
end
it 'Overwriting attributes in a factory' do
customer = create(:cust... |
$:.push File.expand_path("../lib", __FILE__)
# Maintain your gem's version:
# require "jquery-raty-rails/version"
# Describe your gem and declare its dependencies:
# Gem::Specification.new do |s|
# s.name = "jquery-raty-rails"
# s.version = JqueryRatyRails::VERSION
# s.authors = ["Brian M. Clappe... |
class Dog
attr_accessor :name, :breed
def initialize(name, breed="Mutt")
@name = name
@breed = breed
end
def breed(breed = "Mutt")
"#{@breed}"
end
end
# mutt = Dog.new
# mutt.breed = "Mutt"
|
class TimelineController < UIViewController
include BW::KVO
attr_accessor :current_room
# ---------- viewcontroller life cycle ----------
def viewDidLoad
puts "[TL] viewDidLoad"
super
self.edgesForExtendedLayout = UIRectEdgeNone
rmq.stylesheet = TimelineControllerStylesheet
init_nav
rmq... |
class CategoryProduct < ActiveRecord::Base
attr_accessible :category_id, :product_id
validates :category_id, :product_id, :presence => true
belongs_to :product
belongs_to :category
end
|
require "rails_helper"
describe OrdersController do
describe 'new_email' do
before do
@user = User.create(email: 'becarella@gmail.com')
post :create, {
envelope: {
from: 'becarella@gmail.com',
to: 'test@example.com'
},
headers: {
subject: 'ch... |
require "application_system_test_case"
class UserTaggedsTest < ApplicationSystemTestCase
setup do
@auth_admin_user_tagged = auth_admin_user_taggeds(:one)
end
test "visiting the index" do
visit auth_admin_user_taggeds_url
assert_selector "h1", text: "User Taggeds"
end
test "creating a User tagge... |
require 'open-uri'
require 'nokogiri'
class Feed::Blog < Feed
def self.default
new(name: 'My Blog', info: 'your blog url')
end
def url=(info)
if info
new_url = info.normalize_url
new_url.insert(0, 'http://') unless info.match /^http/
if doc = Nokogiri(open new_url) rescue nil
... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
private
def authenticate_user!
unless logged_in?
redirect_to login_url, flash: { warning: 'ログインしてください。' }
end
end
def set_item
@item = Item.find(params[:item_id])
end
... |
# encoding: utf-8
module HireFire
module Macro
module Que
QUERY = %{
SELECT count(*) AS total,
count(locks.job_id) AS running,
coalesce(sum((error_count > 0 AND locks.job_id IS NULL)::int),... |
class DogsController < ActionController::Base
before_action :get_dog, only: [:show, :edit, :update]
def index
@dogs = Dog.all
end
def show
end
def edit
end
def update
@dog.update(dog_params)
redirect_to @dog
end
private
def get_dog
@dog = Dog.find(params[:id])
end
def d... |
require './lib/connect4.rb'
describe Board do
describe "#initialize" do
it "creates a new empty game board" do
game = Board.new
expect(game.board).to eql(Array.new(6*7,0))
end
end
describe "#get_pos" do
it "returns nil for an empty position" do
ga... |
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
# Define your WIN_COMBINATIONS constant
WIN_COMBINATIONS = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
def won?(board)
WIN_COMBINATIONS.find do |combination|
win_index1 = combination[0]
win_index... |
class SentenceGenerator::Generator
def generate_sentences(options={})
per_page = options.delete(:offset) || 10
page = options.delete(:page) || 1
Sentence.paginate(per_page: per_page, page: page)
end
end
|
# frozen_string_literal: true
require 'sinatra/base'
require 'jiji/web/services/abstract_service'
module Jiji::Web
class RateService < Jiji::Web::AuthenticationRequiredService
include Jiji::Model::Trading::Internal
options '/range' do
allow('GET,OPTIONS')
end
get '/range' do
ok(tick_r... |
# 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 bin/rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# ... |
require 'spec_helper'
describe TestSuite do
it "should let us make add a new one" do
test_suite = FactoryGirl.create(:test_suite)
test_suite.save.should be_true
end
it "should require an name" do
test_suite = FactoryGirl.build(:test_suite, name: nil)
test_suite.should_not be_valid
test_suite.... |
describe User do
before(:each) { @user = User.new(email: 'test@bol.com.br') }
subject{ @user }
it { should respond_to(:email) }
it "#email returns a string" do
expect(@user.email).to match 'test@bol.com.br'
end
end |
require './f5'
require 'optparse'
require 'pp'
require 'ostruct'
class Optparser
def self.parse(args)
options = OpenStruct.new
opts = OptionParser.new do |opts|
opts.banner = "Usage: f5_gtm_set_ipv6_no_error_response_state.rb [options]"
opts.separator ""
opts.separator "Specific opt... |
require 'rails_helper'
require File.join(Rails.root, "script", "queries", "overlapping_plan_years")
describe 'plan_year_overlap?' do
it 'should return true if there are overlapping plan years' do
employer = FactoryGirl.create :employer
bad_plan_year = FactoryGirl.create :overlapping_plan_year
bad_plan_year.emp... |
class Comment < ActiveRecord::Base
validates :body, :user_id, :commentable_id, :commentable_type, presence: true
has_many :likes, as: :likeable, dependent: :destroy
belongs_to :commentable, polymorphic: true
belongs_to :user
def liked_by?(user)
self.likes.exists?(user_id: user.id)
end
def like_of(... |
# frozen_string_literal: true
require 'delegate'
require 'singleton'
require 'logger'
module ArchUpdate
# Singleton Logger
class Logger < Delegator
include Singleton
DEFAULT_LEVEL = ::Logger::Severity::INFO
attr_reader :base
def initialize
init(STDOUT, level: DEFAULT_LEVEL)
end
d... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
# 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: 'Emanue... |
class ManageIQ::Providers::Kubevirt::InfraManager::Vm < ManageIQ::Providers::InfraManager::Vm
include_concern 'Operations'
POWER_STATES = {
'Running' => 'on',
'Pending' => 'powering_up',
'Scheduling' => 'powering_up',
'Scheduled' => 'off',
'Succeeded' => 'off',
'Failed' => 'off'... |
class PostSerializer < ActiveModel::Serializer
attributes :id, :body, :user, :sent_to_user, :created_at, :updated_at, :reply_post
has_many :reply_posts
end
|
class CreateFlights < ActiveRecord::Migration[5.2]
def change
create_table :flights do |t|
t.integer :duration
t.date :departure_date
t.string :departure_airport_id
t.string :arrival_airport_id
t.timestamps
end
add_index :flights, :departure_airport_id
add_index :flights... |
class ApplicationController < ActionController::Base
config.time_zone = 'Pacific Time (US & Canada)'
protect_from_forgery with: :exception
def user_signed_in?
if session[:user_id].present? && current_user.nil?
session[:user_ud] = nil
end
session[:user_id].present?
end
helper_method :user_s... |
module DuoApi
module Util
DuoApiError = Class.new(StandardError)
def stringify_hash(hash)
hash ||= {}
Hash[hash.map { |k, v| [k.to_s, v] }]
end
def error_with_message(message)
klass = Class.new(DuoApiError)
klass.send :define_method, :initialize do |*msg|
msg = msg.fi... |
require 'spec_helper'
describe EmailValidator do
let(:described_class) { EmailValidator }
describe :validate_each do
let(:validator) { described_class.new(options) }
let(:options) { { attributes: [attribute] } }
let(:record) { double('ActiveRecord::Base', errors: errors) }
let(:errors) { double('A... |
module Naf
class MachineRunnersController < Naf::ApplicationController
before_filter :set_rows_per_page
def index
respond_to do |format|
format.html
format.json do
set_page
@total_records = ::Naf::MachineRunner.count(:all)
@rows = ::Logical::Naf::MachineR... |
require 'spec_helper'
require 'elasticsearch/persistence/model'
describe OrmAdapter::Elasticsearch do
before do
class ThingModel
include Elasticsearch::Persistence::Model
attribute :email, String, mapping: { type: 'string', index: 'not_analyzed' }
end
ThingModel.create_index!
end
after d... |
class CreateAddresses < ActiveRecord::Migration[5.1]
def change
create_table :addresses do |t|
t.string :street, null: false
t.string :city, null: false
t.string :state, null: false
t.string :zip_code, null: false
t.string :suite
t.string :tenant_first_name
t.string :tenant_last... |
class GeoNotesController < ApplicationController
require 'securerandom'
def index
render json: GeoNote.all
end
def show
render json: GeoNote.find(params.require(:id))
end
def create
create_params = params
.require(:geo_note)
.permit(:device_id, :latitud... |
class ChangeUserRelationshipsToBeingFollowedId < ActiveRecord::Migration
def change
remove_column :user_relationships, :followed_id
add_column :user_relationships, :being_followed_id, :integer
add_index :user_relationships, :being_followed_id
add_index :user_relationships, [:follower_id, :being_followe... |
class RemoveLlevarFromComandaComidas < ActiveRecord::Migration
def change
remove_column :comanda_comidas, :llevar, :boolean
end
end
|
class DietsController < ApplicationController
skip_after_action :verify_authorized
def new
@diet = Diet.new
end
def create
@diet = Diet.new(diet_params)
if @diet.save
redirect_to root_path
else
render :new
end
end
private
def diet_params
params.require(:diet).permit(... |
namespace :statuses do
params do
requires :user_id, type: Integer, desc: 'A user ID'
end
namespace ':user_id' do
desc "retrueve a user's status"
params do
requires :status_id, type: Integer, desc: 'A status ID'
get ':status_id' do
User.find(params[:user_id]).statuses.find(params[:status_id])
end
... |
module Genre
POP, CLASSIC, JAZZ, ROCK = *1..4
end
$genre_names = ['Null', 'Pop', 'Classic', 'Jazz', 'Rock']
class Album
attr_accessor :title, :artist, :genre, :tracks
def initialize (_title, _artist, _genre, _tracks)
@title = _title
@artist = _artist
@genre = _genre
@tracks = _tracks
end
end
class Trac... |
module AuxiliaryAddons
module JscriptHelper
# ::Rails.logger.error("...")
#
# Common JScript helpers
#
#
def set_focus_on_load(id)
if ::AuxiliaryAddons.options[:use_prototype]
javascript_tag("Event.observe(window, 'load', $('#{id}').focus());")
end
if ::AuxiliaryAdd... |
class PagesController < ApplicationController
def home
redirect_to articles_path
end
end
|
module CDI
module V1
class PostSurveyToSubscribersWorker
include Sidekiq::Worker
sidekiq_options :retry => 5, queue: :publishers
sidekiq_retry_in { |count| count * 60 }
def perform survey_type, survey_id
survey = survey_type.constantize.find survey_id
service = ::CDI::V... |
class AddExtraSalesToReport < ActiveRecord::Migration
def change
add_column :reports, :extra_sales, :integer, :after => :sales, :default => 0
end
end
|
require "spec_helper"
RSpec.describe "Day 17: Two Steps Forward" do
let(:runner) { Runner.new("2016/17") }
describe "Part One" do
it "finds the shortest path for a passcode" do
expect(runner.execute!("ihgpwlah", part: 1)).to eq("DDRRRD")
expect(runner.execute!("kglvqrro", part: 1)).to eq("DDUDRLRR... |
class RulesController < ApplicationController
def new
@rule = RuleForm.new
end
def create
@rule = RuleForm.new rule_params
if @rule.save
redirect_to root_path, notice: "Rule saved"
else
render :new
end
end
private
def rule_params
params.require(:rule).permit(:pattern, ... |
module Smtp
class ContentDisposition
ATTACHMENT = 'attachment'.freeze
def initialize(type, filename)
@type = type
@filename = filename
end
def as_header
@header ||= HeaderWithParams.new(Header::CONTENT_DISPOSITION, @type,
filename: @filename)
... |
module PPC
class Baidu
class Account < ::PPC::Baidu
def initialize(params = {})
params[:service] = 'Account'
super(params)
end
def info
response = request('getAccountInfo')["accountInfoType"]
end
def all(params = {})
download(params)
end
... |
#!/usr/bin/env ruby
require 'open3'
module Failover
class Redis
attr_reader :nodes
attr_reader :sleep_interval
attr_reader :config, :inspector
def initialize
File.open("/etc/default/redis-failover").each_line do |line|
kv = line.split("=").map(&:strip)
case kv[0]
when ... |
class NameValidator
def initialize(name)
@name = name
end
def is_valid?
has_only_letters_or_dashes &&
has_more_than_two_words &&
has_only_one_space_between_words &&
has_capitalized_words &&
has_first_letter_after_dash_capitalized &&
has_only_first_letter_capitalized
end
private
... |
require 'test_helper'
class UserFavoritesControllerTest < ActionController::TestCase
setup do
@user_favorite = user_favorites(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:user_favorites)
end
test "should get new" do
get :new
assert... |
require 'rails_helper'
RSpec.describe User, type: :model do
# pending "add some examples to (or delete) #{__FILE__}"
subject {
User.new(
name: 'User',
email: 'user@test.com',
password: '123456',
password_confirmation: '123456')
}
describe 'Validations' do
# vali... |
FactoryGirl.define do
factory :friendship do
association :friender, class: User, factory: :user
association :friended, class: User, factory: :user
accepted true
created_at {Time.now}
end
end
|
class RentItemsController < ApplicationController
include ApplicationConcern
before_action :set_rent_item, only: %i[repay]
before_action :set_borrowed_item, only: %i[show edit update]
def rent_form
@rent_item = RentItem.new(item: item)
@rent_item.tenant = Contact.new
render partial: 'items/popups/... |
class RegistrationService < ApplicationService
@@password_regex = /^(?=.*[a-zA-Z])(?=.*[0-9]).{8,}$/
def initialize(sign_up_params)
super()
@sign_up_params = sign_up_params
@errors = []
end
def json_view
{ user: @user.as_json(except: [:password, :created_at]) }
end
def sign_up
valida... |
require "nokogiri"
Fy::App.helpers do
def inline_svg(filename, transform_params={})
svg_contents = File.open("app/views/#{filename}").read
document = Nokogiri::XML::Document.parse(svg_contents)
svg = document.at_css "svg"
transform_params.keys.each do |key|
svg[key] = transform_params[key]
... |
# require 'pry'
# # 1.
# # 1. (32 * 4) >= 129 => false
# # 2. false != !true => false
# # 3. true == 4 => false
# # 4. false == (847 == '874') => true
# # 5. (!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false => true
# # Write a method that takes a string as argument.
# # The method should return the all-ca... |
class Track < ApplicationRecord
validates :title, :ord, :album_id, presence: true
belongs_to :album,
dependent: :destroy
has_one :band,
through: :album,
source: :band
has_many :notes
end
|
require "rails_helper"
RSpec.describe DailyTask::StartTimeLog, type: :command do
let(:uom) {SeedUnitOfMeasure.call}
let(:strain) { Common::Strain.create!(name: 'xyz', strain_type: 'indica') }
let(:facility) do
facility = create(:facility, :is_complete)
facility.rooms.each do |room|
room.rows.each d... |
require_relative('message')
class Room
attr_reader :name, :capacity, :room_fee, :individual_fee, :remaining_spaces, :reserved, :till_amount, :current_tab
def initialize(name, capacity, room_fee, till_amount=100)
@name = name
@capacity = capacity
#Room is initially empty
@remaining_spaces = capaci... |
class SeriesTrack < ApplicationRecord
belongs_to :track
belongs_to :series
end
|
require "rails_helper"
RSpec.describe User, type: :model do
it { should have_many(:bucketlists).with_foreign_key("created_by") }
it { should have_many(:tokens) }
it { should validate_presence_of(:firstname) }
it { should validate_presence_of(:lastname) }
it { should validate_presence_of(:email) }
it { shou... |
class UsersController < ApplicationController
before_action :authenticate_user!
def dashboard
@subscription = Subsription.find_by_user_id(current_user.id)
if @subscription.present?
@plan = Stripe::Plan.retrieve(@subscription.plan_id)
end
end
def show
@user = User.find(params[:id])
@... |
if RUBY_PLATFORM == 'java'
require_relative 'executor'
module Concurrent
# @!macro single_thread_executor
class JavaSingleThreadExecutor
include JavaExecutor
include SerialExecutor
# Create a new thread pool.
#
# @see http://docs.oracle.com/javase/tutorial/essential/concurre... |
name 'pg_bouncer'
maintainer 'Jeffrey Hulten'
maintainer_email 'jhulten@gmail.com'
license 'Apache v2.0'
description 'Installs/Configures pg_bouncer'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.2.1'
source_url 'https://github.com/jhulten/pg_bouncer-cookbook'
issues_url 'https://... |
require 'spec_helper'
class Shell
include Space::Shell
commands :list => 'ls -al'
end
describe Space::Shell do
let(:shell) { Shell.new('path') }
describe '.commands' do
it 'defines the commands this class cares about' do
Shell.commands[:list].should == 'ls -al'
end
end
describe 'initializ... |
class CreateTenants < ActiveRecord::Migration
def change
create_table :tenants do |t|
t.string :title
t.string :firstname
t.string :surname
t.date :dateofbirth
t.integer :telno
t.string :contact_type
t.string :email
t.timestamps
end
end
end
|
require File.dirname(__FILE__) + '/spec_helper'
require "stringio"
# TODO CHECK FOR NO THEMES!
describe Ansuz::Installer do
describe "creating a database.yml" do
before(:each) do
@stdin = StringIO.new("","r+") # Fake STDIN
@stdout = StringIO.new("","r+")
@installer = Ansuz::Installer.ne... |
class AddAttachmentDataToArticleMessages < ActiveRecord::Migration[5.2]
def change
add_column :article_messages, :attachment_data, :text
end
end
|
require 'spec_helper'
describe Halo do
describe "configuration" do
it "loads its configuration from the .yaml file on creation" do
halo = Halo.new
halo.client_id.should_not be nil
halo.client_secret.should_not be nil
end
end
describe "authentication" do
it "is marked as authenticated on s... |
class StoryComment < ActiveRecord::Base
attr_accessible :content, :story_id, :user_id
belongs_to :user
belongs_to :story
validates :content, presence: true
validates :user_id, presence: true
validates :story_id, presence: true
default_scope order: 'story_comments.created_at DESC'
end
|
require 'libusb'
require 'color'
module DreamCheeky
class Notifier
def self.all
@@devices ||= LIBUSB::Context.new.devices(idVendor: 0x1d34, idProduct: 4).sort.map {|device| new (device)}
end
def initialize(device)
@device = device
reset_device
end
def colour!(colour)
sen... |
class Place < ApplicationRecord
validates :name, presence: true, length: {maximum: 50}
validates :description, presence: true, length: {maximum: 500}
mount_uploader :picture, PictureUploader
validate :picture_size
validates :picture, presence: true
belongs_to :user
has_many :likes
private
def picture_size
... |
#Arrays
#-------- Creating Arrays -----------
array_1 = Array.new #creates an empty array
array_2 = Array.new(5) #creates an array with 5 spaces. The default values are nil
array_3 = Array.new(5, "empty") # creates an array with 5 spaces, and the default space will store the string "empty"
array_4 = [1, 2, "thre... |
class EventSerializer < EventIndexSerializer
has_many :attendees
belongs_to :group, serializer: EventGroupSerializer
attribute :creator
def creator
object.user.username
end
end
|
require 'test_helper'
class ActiveCodeTest < ActiveSupport::TestCase
fixtures :users
self.use_instantiated_fixtures = true
test "new user codes are generated correctly" do
code1 = @bob.new_active_code('password-reset')
assert_not_nil code1
assert_equal 'password-reset', code1.section
assert_equa... |
class ProductFamily < ActiveRecord::Base
belongs_to :product_category
has_many :products, dependent: :destroy
validates_presence_of :product_category_id, :name, :sample_code
validates_uniqueness_of :name
end
|
#Add remote data source and pull in stories from Reddit, Mashable and Digg.
# http://mashable.com/stories.json
#http://www.reddit.com/r/aww/.json
# These stories will also be upvoted based on our rules. No more user input!
# Pull the json, parse it and then make a new story hash out of each story(Title, Category, ... |
class CreateSubscribers < ActiveRecord::Migration
def self.up
create_table :subscribers do |t|
t.string :device_id
t.string :push_id
t.timestamps
end
execute "ALTER TABLE `subscribers` ADD `type` ENUM('sms', 'android', 'iphone')"
execute "ALTER TABLE `subscribers` ADD `active` ENUM(... |
class AjaxController < ApplicationController
include HTTParty
base_uri 'http://api.thisismyjam.com'
def search_by_artist
@qry_parameter = params[:search] if params[:search]
@tracks_data = tracks(@qry_parameter)
@results = @tracks_data.parsed_response
end
def tracks(query)
options = ... |
require 'test/unit'
require 'rubygems'
require 'nokogiri'
require 'repub/epub'
class TestToc < Test::Unit::TestCase
def test_toc_create
ncx = Repub::Epub::NCX.new('some-ncx')
s = ncx.to_xml
#p s
doc = Nokogiri::XML.parse(s)
assert_equal('some-ncx', doc.at("//xmlns:meta[@name='dtb:uid']")['content... |
class CommentsController < ApplicationController
def index
@comments = Comment.all
end
def new
@comment = Comment.new
end
def edit
end
def create
@comment = Comment.new(comment_params)
if @comment.save
flash[:success] = 'Your comment was successfully added!'
redirect_to article_u... |
feature 'user sign up' do
scenario 'I can sign up as a new user' do
expect { sign_up }.to change(User, :count).by 1
expect(page).to have_content('Welcome, rich@gmail.com')
expect(User.first.email).to eq('rich@gmail.com')
end
scenario 'requires a matching confirmation password' do
expect { sign_u... |
require 'spec_helper'
module GameOfLife
describe Cell do
before(:each) do
@cell = Cell.new([1,1])
end
it "should respond with a position of 1,1" do
expect(@cell.position).to eq [1,1]
end
it "should be alive as a default" do
expect(@cell.state).to eq :live
end
end
end
|
# hours in a year
seconds_in_minute = 60
minutes_in_hour = 60
hours_day = 24
days_year = 365
days_leap_year = days_year + 1
seconds_in_hour = 3600
seconds_in_day = (seconds_in_minute * minutes_in_hour) * hours_day
puts "There are #{seconds_in_day} seconds in one day."
hours_in_year = (hours_day * days_year)
hours_... |
require_relative 'abstract_resource'
module FbResource
class Device < AbstractResource
self.path = '/api/device/'
# Alias for #all() because #all() makes no sense on a singular resource.
def current
all
end
end
end
|
module LinksHelper
def voteTally(link)
Vote.sum(:value, :conditions => ['link_id = ?', link.id])
end
def voteTallyColor(link)
if voteTally(link) > 0
theClass = "green"
elsif voteTally(link) < 0
theClass = "red"
end
theClass
end
def userVotedPlus?(link)
p... |
class CreateCertificate < ActiveRecord::Migration
def change
create_table(:certificates) do |t|
t.integer :customer_id
t.integer :merchant_id
t.string :code
t.integer :amount
t.boolean :transaction_costs_included
t.string :status, :default => 'unredeemed'
t.timestamps
... |
# -*- coding: utf-8 -*-
=begin
Faça um programa que peça dois números, base e expoente, calcule e mostre o
primeiro número elevado ao segundo número. Não utilize a função de potência da
linguagem
=end
puts "=============================================================="
puts "Digite o primeiro numero: "
num1 = gets.... |
class FontHennyPenny < Formula
head "https://github.com/google/fonts/raw/main/ofl/hennypenny/HennyPenny-Regular.ttf", verified: "github.com/google/fonts/"
desc "Henny Penny"
homepage "https://fonts.google.com/specimen/Henny+Penny"
def install
(share/"fonts").install "HennyPenny-Regular.ttf"
end
test do
... |
class Coupon < ApplicationRecord
self.table_name = 'coupons'
after_initialize :init
validates_presence_of :code, :expiry_at, :discount, :discount_type
validates_inclusion_of :discount_type, in: Constants.DiscountTypeValues
def expired?
expiry_at < Time.now
end
private
def init
self.discount_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.