text stringlengths 10 2.61M |
|---|
class CreateRooms < ActiveRecord::Migration[5.1]
def change
create_table :rooms do |t|
t.references :house, foreign_key: true, null: false
t.string :room_type, null: false
t.string :name
t.integer :rent, null: false
t.integer :common_expense
t.integer :deposit
t.string :s... |
class ArticlesController < ApplicationController
before_action :page_meta, only: :index
def index
@articles = Article.order(created_at: :desc)
end
def show
@article = Article.find_by(permalink: params[:id])
if @article.blank?
redirect_to articles_path
flash[:alert] = 'Page Not Fo... |
class AddHostColumnToProperty < ActiveRecord::Migration
def self.up
add_column :properties, :host, :string, :limit => 70
add_index :properties, :host
# Update each property to trigger setting of host column
#Property.all.each {|p| p.url_will_change!; p.save!}
end
def self.down
remov... |
require 'open-uri'
require 'nokogiri'
module ResultsGrabber::GetResults
RESULTS_URL = "http://www.bbc.co.uk/sport/football/results/partial/competition-118996114?structureid=5"
def get_results # Get me all results
doc = Nokogiri::HTML(open(RESULTS_URL))
days = doc.css('.table-header').each do |h2_tag|
date = Date.... |
# Represents a comment. Comments are attached to both a post and a user.
class Comment < ActiveRecord::Base
default_scope { where(is_deleted: false) }
belongs_to :post, :polymorphic => true
belongs_to :user
end
|
# -*- coding: utf-8 -*-
#
# Copyright 2013 whiteleaf. All rights reserved.
#
require_relative "../inventory"
require_relative "../novelsetting"
module Command
class Setting < CommandBase
def self.oneline_help
"各コマンドの設定を変更します"
end
class InvalidVariableType < StandardError
def initialize(type... |
Rails.application.routes.draw do
# list all the controllers for device
devise_for :users, :controllers => {
confirmations: "users/confirmations",
omniauth: "users/omniauth",
passwords: "users/passwords",
registrations: "users/registrations",
sessions: "users/sessions",
unlocks: ... |
class Guide::ScenarioLayoutView
def initialize(node:, node_title:, scenario:, format:, injected_html:)
@node = node
@node_title = node_title
@scenario = scenario
@format = format
@injected_html = injected_html
end
def node_title
@node_title
end
def scenario_name
@scenario.name
... |
def echo(hello)
return hello
end
def shout(hello)
return hello.upcase!
end
def repeat(word, num = 2)
str = ""
num.times {str += " #{word}"}
str.slice!(0)
return str
end
def start_of_word(string, num)
new_str = string.dup
return new_str.slice!(0,num)
end
def first_word(string)
new... |
json.array!(@materia_carreras) do |materia_carrera|
json.extract! materia_carrera, :id, :materia_id, :carrera_id, :semestre
json.url materia_carrera_url(materia_carrera, format: :json)
end
|
class AskMeAnything
def method_missing(method_name)
"You called #{method_name}"
end
end
object = AskMeAnything.new
puts object.this_method_is_not_defined
puts object.also_undefined
|
# frozen_string_literal: true
require_relative 'display'
# move class gets user moves and validates
class Move
include Display
def initialize
@first_move = true
end
def valid_move(move, board_entry)
p board_entry
if board_entry.nil? || move <= 1 && move >= 9
# puts 'Invalid move. Enter 1 to... |
module Media
module Helper
class Size
def initialize(args)
@width = args.fetch(:width)
@height = args.fetch(:height)
end
def to_s
[@width, @height].join('x')
end
end
end
end
|
class AddNeedsPpsrToStock < ActiveRecord::Migration
def change
add_column :stocks, :needs_ppsr, :boolean, :default => true
end
end
|
class Test
CONSTANT = 1
def blah
"blah"
end
end
|
# frozen_string_literal: true
class EffortTimesRowSerializer < BaseSerializer
attributes *EffortTimesRow::EXPORT_ATTRIBUTES, :display_style, :stopped, :dropped, :finished
attribute :elapsed_times, if: :show_elapsed_times
attribute :absolute_times, if: :show_absolute_times
attribute :segment_times, if: :show_se... |
class Currency
attr_reader :amount, :code
def initialize(amount:, code:)
@amount = amount
@code = code
end
def ==(other)
@amount == other.amount && @code == other.code
end
def +(other)
if @code == other.code
Currency.new(amount: @amount + other.amount, code: @code)
end
end
en... |
# =============================================================================
#
# MODULE : test/test_thread_pool_queue.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# ==========================================================================... |
FactoryGirl.define do
factory :southern_minute, :class => Refinery::SouthernMinutes::SouthernMinute do
sequence(:headline) { |n| "refinery#{n}" }
end
end
|
RSpec.describe DatabasePlumber do
let(:report_class) { DatabasePlumber::Report }
let(:current_example) { self }
before(:each) do
allow(report_class).to receive(:on)
described_class.log current_example
end
context 'with no leaks' do
before(:each) do
described_class.inspect
end
it ... |
class StudentsController < ApplicationController
def index
@students = Student.all
end
# Automatically opens and renders the associated view.
# app/views/students.index/html.erb.
# Also all instance variables created within the
# action are shared within the associated view
def show
@student = S... |
# encoding: utf-8
module Rudeki::Error
def initialize(value = "RUDEKI ERROR")
show_error if Rudeki::Config.errors
super(value)
end
def show_message(title, messages = [])
rudeki_info "╔══════════ #{title} ══════════"
messages.each { |message| rudeki_info "║ #{message}" }
rudeki_info "╚══════... |
#!/usr/bin/env ruby
require 'date'
require './euler'
class Nineteen < Euler
def run(unbound=0)
num_of_sundays = 0
start_date = Date.new(1901,1,1)
end_date = Date.new(2000,12,31)
while start_date < end_date do
num_of_sundays += 1 if start_date.wday == 0
start_date = start_date >> 1
... |
class CreateEsteemPersonals < ActiveRecord::Migration[5.0]
def change
create_table :esteem_personals do |t|
t.decimal :amount, precision: 10, scale: 2, default:0.00
t.string :condominius_id
t.references :row, index: true
t.references :year, index: true
t.timestamps null: false
e... |
# frozen_string_literal: true
require 'test_helper'
require 'minitest/stub_any_instance'
module Admin
class DocumentsControllerTest < ActionController::TestCase
setup do
@document = documents(:one)
@document2 = documents(:two)
sign_in AdminUser.create!(email: 'admin@example.com', password: 'p... |
module Alimento
#Esta clase permite representar un plato
class Plato
attr_accessor :name, :vegetales, :frutas, :granos, :proteinas, :aceites
#Se guarda el nombre del plato y se recibe un bloque con los ingredientes
def initialize(name, &block)
@name = name
@vegetales = []
@fruta... |
class RegistrationsController < Devise::RegistrationsController
protected
def afer_sign_up_path_for(resource)
"/voters/#{resource_.id}/edit"
end
end
|
#!/usr/bin/env ruby
def graphArray(array)
array.each_with_index do |count, ac|
printf "%02d|%s\n", ac, ('#' * count)
end
end
min = 15
max = 15
total = 0
count = 0
acs = Array.new(30, 0)
raw = Array.new
Dir.foreach('./bestiary/_posts/') do |path|
next if path == '.' or path == '..'
path = './bestiary/_... |
# -*- encoding: utf-8 -*-
Gem::Specification.new do |gem|
gem.name = 'motion-blitz'
gem.version = '1.2.0'
gem.authors = ['Devon Blandin']
gem.email = 'dblandin@gmail.com'
gem.description = %q{RubyMotion wrapper for SVProgressHUD}
gem.summary = %q{RubyMotion wrapper for S... |
require 'spec_helper'
require 'yt/errors/unauthorized'
describe Yt::Errors::Unauthorized do
let(:msg) { %r{^A request to YouTube API was sent without a valid authentication} }
describe '#exception' do
it { expect{raise Yt::Errors::Unauthorized}.to raise_error msg }
end
end |
json.array!(@sections) do |section|
json.extract! section, :session_id, :teacher_id, :room, :subject, :description, :capacity
json.url section_url(section, format: :json)
end
|
# == Schema Information
#
# Table name: reports
#
# id :integer not null, primary key
# cell_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Report < ActiveRecord::Base
validates_uniqueness_of :cell_id
attr_accessible :id, :cell_id
belongs... |
require "formula"
class EyeD3 < Formula
homepage "http://eyed3.nicfit.net/"
url "http://eyed3.nicfit.net/releases/eyeD3-0.7.5.tgz"
sha1 "bcfd0fe14f5fa40f29ca7e7133138a5112f3c270"
bottle do
cellar :any
sha1 "fddbdc445f3d6f89f1c57dd656cef69263b9335d" => :mavericks
sha1 "fe13d924e6d1f85922930784f3b34... |
require 'test_helper'
require 'sidekiq/testing'
class LaborTest < ActiveSupport::TestCase
test "Importar CSV labores de fertilizacion" do
UploadWorker.jobs.clear
file = File.open 'test/files/labores.csv'
Labor.importar file, 'fertilizadoras'
assert UploadWorker.jobs.count == 1
UploadWorker.drai... |
require 'spec_helper'
describe Parser do
describe ".parse" do
it "should return a sexp for a non-empty string" do
expect(Parser.parse("abc")).to be_instance_of(Sexp)
end
it "should return nil for an empty string" do
expect(Parser.parse("")).to be_nil
end
it "should return literal se... |
FactoryGirl.define do
factory :pcares_event, :class => Refinery::OurOffices::PcaresEvent do
sequence(:category) { |n| "refinery#{n}" }
end
end
|
class Client < ActiveRecord::Base
has_many :samples, dependent: :destroy, inverse_of: :client
has_many :exams, through: :participations
has_many :participations, dependent: :destroy
accepts_nested_attributes_for :samples, reject_if: lambda { |a| a[:sample_code].blank? || a[:sample_type].blank? }
validates :... |
require 'spec_helper'
describe Enocean::Esp3::BasePacket do
let(:packet) { Enocean::Esp3::BasePacket.new(0x9, [ 0x8 ], [ 0x9 ]) }
it "should serialze the packet correctly" do
packet.serialize.should == [ 0x55, 0x00, 0x01, 0x01, 0x9, 0x41, 0x8, 0x9, 0x97 ]
end
it "should be able to print the packet" do
... |
class AddressesController < ApplicationController
before_action :set_address, only: [:edit, :update]
def create
@address = Address.new(address_params)
if @address.save
redirect_to :credit_card_user_registration
else
render "devise/registrations/address"
end
end
def edit
end
de... |
require_relative '../spec_helper'
describe package('docker-engine') do
it { should be_installed }
end
describe service('docker') do
it { should be_enabled }
it { should be_running }
end
describe group('docker') do
it { should exist }
end
describe file('/var/run/docker.sock') do
it { should be_socket }
i... |
# frozen_string_literal: true
require_relative 'importer'
importer = Taroxd::Importer.new 'javascript', 'mvmz-plugins/_posts'
source = 'C:/Users/taroxd/MVMZ-plugins'
namespace 'mvmz' do
desc 'import mvmz plugins to _posts directory'
task :import do
files = Dir.chdir(source) { `git ls-files js` }.lines
fil... |
# Some bettertabs specifications:
#
# * Should always work with javascript disabled (using the urls of the tabs links)
# * The bettertabs hepler should accept:
# * args: (bettertabs_id, options)
# * options can be:
# * :selected_tab => tab_id to select by default.
# It is be overr... |
require File.dirname(__FILE__) + '/spec_helper.rb'
require 'json'
describe "rslt" do
describe "When a developer wants to transform their hello world xml" do
before do
module TestHelper
def error_text_in_parent(options=nil)
error("Text is not allowed within a parent node! Options were #{... |
class MeetingsController < ApplicationController
before_action :find_meeting, only: [:show]
def index
@meetings = current_user.meetings
end
def new
@meeting = current_user.meetings.build
end
def create
@meeting = current_user.meetings.build(meeting_params)
if @meeting.save
flash[:n... |
#!/usr/bin/env ruby
# Create practice string variable
practice_string = 'this is a string to practice with'
# Display the original string
puts practice_string
# Display the string capitalized
puts practice_string.capitalize
# Display the string in all uppercase
puts practice_string.upcase
# Display the string with... |
require 'sssa'
require 'net/http'
require 'uri'
require 'json'
require 'yaml'
module SSSaaS
module API
def self.from_yaml(data, key)
obj = YAML.load(data)
return self.from_config(obj[key])
end
def self.from_config(obj)
if obj.nil?
return... |
require 'rails_admin/adapters/mongoid'
module RailsAdmin
module Adapters
module MongoidNested
def new(params = {})
::RailsAdmin::Adapters::Mongoid::AbstractObject.new(parent_object.send(association_name).new(params))
end
def get(id)
::RailsAdmin::Adapters::Mongoid::AbstractObje... |
# frozen_string_literal: true
require 'uri'
require 'json'
require 'rest-client'
require_relative 'page'
module ScrapBox
class Project
attr_reader :id, :name, :url
def initialize(data, client)
@id = data[:id]
@name = data[:name]
@url = "https://scrapbox.io/#{@name}"
@client = clien... |
class MoviesController < ApplicationController
def index
@movies = Movie.all
end
def show
@movie = Movie.find(params[:id])
end
def new
@movie = Movie.new
end
def create
@movie = Movie.create!(movie_params)
redirect_to "/movies/#{@movie.id}"
end
def edit
@movie = Movie.find(params[:id])
end
... |
class FinishOrderExecutionsJob
MAX_VALID_TIME = 5.minutes
include Sidekiq::Worker
def perform
executions.each do |order_execution|
PlaceOrderService.new(order_execution.user, order_execution).execute
end
end
private
def executions
OrderExecution.where("created_at > ?", MAX_VALID_TIME.ago... |
# Use Hash#select to iterate over numbers and return a hash
# containing only key-value pairs where the value is less than
# 25. Assign the returned hash to a variable named low_numbers
# and print its value using #p.
numbers = {
high: 100,
medium: 50,
low: 10
}
low_numbers = numbers.select { |_k, v| v < 25 }
... |
class RunnerTrace
prepend SentryHandler
class Error < StandardError
end
attr_reader :logger
def initialize
@logger = Rails.logger.child(class: self.class.name)
@logger.info msg: "runner trace initialized",
sentry_debug_info: sentry_debug_info
end
def call
Statsd.instance.increment("ru... |
class Project < ApplicationRecord
has_many :project_supplies
has_many :supplies, through: :project_supplies
has_many :user_projects
has_many :users, through: :user_projects
end
|
#!/usr/bin/env ruby
$: << File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'evm'
if current = Evm::Package.current
exec current.bin, *ARGV
else
abort 'EVM: No Emacs selected. Select one using "evm use".'
end
|
class RepliesController < ApplicationController
respond_to :js
before_filter :find_topic
def create
emoticons(params[:reply][:content])
@reply = @topic.replies.build(params[:reply])
@reply.parent = @topic.replies.find(params[:reply_to]) unless params[:reply_to].blank?
@reply.user = current_user
... |
class Specinfra::Helper::DetectOs::Nexus < Specinfra::Helper::DetectOs
def detect
# CentOS has a os-release file too, but this should do the right thing
if File.exists?('/etc/os-release')
contents = {}
File.read('/etc/os-release').split.collect {|x| x.split('=')}.each {|x| contents[x[0]] = x[1]}
... |
class Order < ApplicationRecord
belongs_to :location
belongs_to :user
belongs_to :vehicle
extend Geocoder::Model::ActiveRecord
validates :start, :user_id, :vehicle_id, :end, :location_id, presence: true
after_create :set_price
validate :date_validation, on: :create
def paypal_url(return_path)
... |
require 'oily_png'
require 'digest/sha1'
module OnionRing
def self.run(source_file_name, output_file_name = nil)
output_file_name = source_file_name unless output_file_name
png = ChunkyPNG::Image.from_file(source_file_name)
range_width = OnionRing::calc_trim_range((0...png.width).map{|x| Digest::SHA1.h... |
module Api
module ProjectManagement
class ActivitiesApi < Grape::API
extend Api::Base
resources 'projects' do
desc 'Add volunteer'
params do
requires :user_id
end
post ':id/add_volunteer' do
begin
ProjectServices::Activities.add_volunte... |
class User < ApplicationRecord
validates_uniqueness_of :username
has_secure_password
has_secure_token :auth_token
has_many :monsters
def invalidate_token
self.update_columns(auth_token: nill)
end
def self.validate_login(username,password)
user=find_by(username: username)
if user&&user.authenticate(passwo... |
require 'capistrano-scrip/utils'
Capistrano::Configuration.instance.load do
_cset(:virtualenv_bin) { "virtualenv" }
_cset(:virtualenv_args) { "--system-site-packages" }
_cset(:virtualenv_path) { "#{shared_path}/venv" }
_cset(:python) { "#{virtualenv_path}/bin/python" }
_cset(:pip_bin) { "#{virtualenv_path}/b... |
# encoding: utf-8
describe "remove_prefix" do
subject { mapper.new.call input }
let(:input) do
[
{
user_id: 1,
"user_name" => "joe",
contacts: [
{
"contact.emails" => [
{
:"contact.address" => "joe@doe.com",
"co... |
require 'rails_helper'
include AddressDefaults
RSpec.describe Address, type: :model do
describe 'validations' do
describe 'flat_no' do
it('allows blanks') { expect(addressable_new flat_no: '').to be_valid }
it 'has max' do
expect(addressable_new flat_no: 'a' * (MAX_NUMBER + 1)).not_to be_vali... |
class MadesController < ApplicationController
before_action :set_made, only: [:show, :edit, :update, :destroy]
# GET /mades
# GET /mades.json
def index
@mades = Made.all
end
# GET /mades/1
# GET /mades/1.json
def show
end
# GET /mades/new
def new
@made = Made.new
end
# GET /mades/1... |
class CashRegister
attr_accessor :total, :discount, :items, :last_transaction
#attr_accessor creates two methods, getter and setter
#will this value change and will I have to change it?
#only has to do with the class
def initialize(discount = 0) #constructor
@total = 0 #Starts at 0. Instance variables can be s... |
### Assignment: Calculator #######
def calculator
puts "Gimmie a number."
num1 = gets.chomp.to_f
puts "Gimmie another number."
num2 = gets.chomp.to_f
puts "What arithmetic would you like to perform on these numbers? (+,-,*,/)"
operation = gets.chomp
result = case operation when "+" then num1 + num... |
require 'test/test_helper'
class SessionsControllerTest < ActionController::TestCase
should_route :get, '/login', :controller => 'sessions', :action => 'new'
def setup
# initialize roles and privileges
BadgesInit.roles_privileges
@user = Factory(:user, :name => "User", :password => 'user', :pas... |
require 'spec_helper'
describe "ChunkUploader" do
include_context 'with_upload'
let(:upload) { Upload.create }
let(:chunk_file) { File.open("spec/chunk.txt") }
describe "#append_chunk_to_file!" do
context "when chunk_id = 1" do
before(:all) do
upload.append_chunk_to_file!(id: 1, data: chun... |
require "json"
# Root ProjectRazor namespace
module ProjectRazor
module Slice
# ProjectRazor Slice Node (NEW)
# Used for policy management
class Boot < ProjectRazor::Slice::Base
# @param [Array] args
def initialize(args)
super(args)
@hidden = true
@new_slice_style = t... |
require "formula"
class Boot < Formula
homepage "https://github.com/tailrecursion/boot"
url "https://github.com/tailrecursion/boot/archive/1.0.5.tar.gz"
sha1 "ea4dbbc18bed8ec1023f2a11a2378278f700c521"
head do
url "https://github.com/tailrecursion/boot.git"
end
depends_on "leiningen"
resource "jar... |
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheese!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
# Call parameters directly
cheese_and_crackers(20, 30)
# Pass in variables
amount_of_cheese = 1... |
class SessionsController < ApplicationController
def new
@ref = params[:ref] if params[:ref]
end
def create
@user = User.find_by username: params[:session][:username]
if @user && @user.authenticate(params[:session][:password])
session[:user_id] = @user.id
if params[:ref]
redirect_t... |
class User < ApplicationRecord
has_secure_password
validates :email_address, {presence: true, uniqueness: true}
validates :password_digest, presence: true
validates :first_name, presence: true
validates :last_name, presence: true
belongs_to :location
has_many :active_connections, -> { ... |
# frozen_string_literal: true
RSpec.describe 'kiosks/show', type: :view do
before do
assign(:kiosk, create(:kiosk))
render
end
it { expect(rendered).to match(/touch/) }
it { expect(rendered).to match(/2/) }
it { expect(rendered).to match(/circ/) }
end
|
class ChallengeVerifier
def self.verify_challenge(signature, challenge)
signature_challenge = signature.signature_properties['challenge']
if signature_challenge == nil || signature_challenge.value == nil || signature_challenge.value != challenge
raise Exception, "Challenge does not match expected valu... |
require 'binary_struct'
require 'fs/ntfs/attrib_file_name'
require 'fs/ntfs/utils'
module NTFS
DIR_INDEX_NODE = BinaryStruct.new([
'Q', 'mft_ref', # MFT file reference for file name (goofy ref).
'S', 'length', # Length of entry.
'S', 'content_len', # Length of $FILE_NAME attrib... |
class Items
attr_reader :name, :price
attr_accessor :color
def initialize(input_options)
@name = input_options[:name]
@price = input_options[:price]
@color = input_options[:color]
end
def description
puts "This #{@name} cost $#{@price}"
end
end
item1 = Items.new(name: "cookie", price: "2"... |
# code here!
class School
attr_reader :name, :roster
attr_writer :roster, :name
def initialize(name, roster={})
@name = name
@roster = roster
end
def add_student(student_name,grade)
@student_name = student_name
@grade = grade
if @roster.size==0
... |
class AnswerLog < ActiveRecord::Base
belongs_to :question
belongs_to :user
attr_accessible :choose, :correct, :section_num, :question_id, :user_id
def times
# この問題を解くのは何回目か
AnswerLog.group(:question_id, :user_id).size[[self.question_id, self.user_id]]
end
end
|
require 'objects/f5_object'
module F5_Object
class Pool < F5_Object
include Resolution
include Assertion
YAML_LOC = YAMLUtils::NET_DEVICE_YAML
CREATION_INFO = {
'name' => { conversion: String },
'members' => { conversion: :comma_separated, alias: 'member names' },
'monitors' => { ... |
require 'pry'
class MP3Importer
attr_accessor :path, :filecollection
def initialize(path)
@path = path
#binding.pry
end
def files
#entries method: Returns an array containing all of the filenames in the given directory.
@filecollection ||= Dir.entries(@path).select {|filename| !File.direct... |
class MessageMailerNewStoryWorker < BaseWorker
def self.category; :notification end
def self.metric; :email end
def perform(story_id, recipient_id)
perform_with_tracking(story_id, recipient_id) do
story = Story.new(id: story_id)
recipient = User.find(recipient_id)
recipient.email_notifier.n... |
#
# Cookbook Name:: mariadb
# Recipe:: _debian_galera
#
# Copyright 2014, blablacar.com
#
# 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
#
# ... |
module Fog
module Compute
class Google
class Mock
def list_zone_operations(_zone)
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
class Real
# @see https://developers.google.com/compute/docs/reference/latest/zoneOperations/... |
require 'spec_helper'
describe Ruboty::Handlers::Gekiron do
before do
allow_any_instance_of(topic).to receive(:gekiron_topic).and_return(gekiron_topic)
end
let(:ruboty) { Ruboty::Robot.new }
let(:topic) { Ruboty::Gekiron::Actions::Topic }
let(:from) { 'kota' }
let(:to) { '#general' }
let(:gekiron_... |
#!/usr/bin env ruby
require 'rtruckboris/rtruckboris'
class Rtruckboris::HeaderParser
def functions
fns=[]
(0..(functions_num() -1)).each do |i|
fns<<get_nth_function(i)
end
fns
end
def unions
us=[]
(0..(unions_num() -1)).each do |i|
us<<get_nth_union(i)
end
us
end
... |
class EasyEntityCustomAttribute < EasyEntityAttribute
attr_reader :custom_field, :assoc
def initialize(custom_field, options={})
super("cf_#{custom_field.id}".to_sym, options)
@custom_field = custom_field
@assoc = options[:assoc]
end
def caption(with_suffixes=false)
@custom_field.translated_n... |
class ThemeController < ApplicationController
before_filter :set_file, :only => :file
after_filter :cache_file, :only => :file
def file
if @file.text?
headers['Content-Type'] = @file.content_type
render :text => @file.data
else
send_data @file.data, :filename => @file.basename.to_s, :ty... |
require 'spec_helper'
describe TournamentEntry do
before(:each) do
@tournament_entry = Factory.build(:tournament_entry)
end
it "should not save the tournament entry without a team name" do
@tournament_entry.team_name = ""
@tournament_entry.save.should_not be_true, "tourteam_nament entry saved withou... |
require_relative '../velocity'
describe Velocity do
describe '#*' do
it 'computes correctly' do
new_velocity = Velocity.new(2.0, 3.0) * 4
expect(new_velocity.angle).to eq 2.0
expect(new_velocity.speed).to eq 12.0
end
end
describe '#+' do
context 'when combining with point' do
... |
# encoding: utf-8
module Rubocop
module Cop
module Lint
# This cop checks whether the end keywords are aligned properly.
#
# For keywords (if, def, etc.) the end is aligned with the start
# of the keyword.
#
# @example
#
# variable = if true
# ... |
module AppBuilder
class FromImage
def self.create_app(options)
template = Template.new(name: "#{options[:image]}_image")
registry = Registry.find_by_id(options[:registry_id])
template.images << Image.new(
name: options[:image],
source: "#{registry.try(:prefix)}#{options[:image]}... |
class Admin::MemberStepsController < ApplicationController
require 'accounting'
require 'securerandom'
require 'payment_processing'
# load_and_authorize_resource param_method: :member_params
skip_authorize_resource :only => :paystack_subscribe
include Wicked::Wizard
include Accounting
... |
# encoding: utf-8
control "V-52463" do
title "The DBMS must provide audit record generation capability for organization-defined auditable events within the database."
desc "Audit records can be generated from various components within the information system. (e.g., network interface, hard disk, modem, etc.). From an... |
class AddTimeToActiveUsersTable < ActiveRecord::Migration
def change
add_column :actives, :updated, :datetime
end
end
|
# Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
module PermissionsConcern
extend ActiveSupport::Concern
def is_admin?
self.permission_level == true
end
end |
require 'test_helper'
class MatchesHelperTest < ActionView::TestCase
test 'returns darker green for bigger SR gain' do
match1 = build(:match, rank: 3573, placement: true, result: :loss)
match2 = build(:match, rank: 3547, prior_match: match1, result: :loss) # -26
match3 = build(:match, rank: 3572, prior_m... |
class Menu < ApplicationRecord
has_many :menus_user
has_many :users , through: :menus_user
has_many :menus_recipes
has_many :recipes, through: :menus_recipes
end
|
class Cart < ActiveRecord::Base
belongs_to :user
has_many :line_items
has_many :items, through: :line_items
def add_item(item_id)
if line_item = self.line_items.find_by(:item_id => item_id)
line_item.quantity += 1
line_item.save
line_item
else
self.line_items.build(:item_id => i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.