text stringlengths 10 2.61M |
|---|
FactoryGirl.define do
factory :idea do |m|
m.name "blue cookies"
m.description "cookies with color of blue"
end
end |
module Ml
class Cluster
def self.score(options={})
new(options).score
end
def initialize(options={})
#puts "got options: #{options.inspect}"
@data_sets = options[:readable_data_sets]
@compressor = options[:compressor]
@compressor_args = options[:compressor_args]
@file_... |
class AddPriorityToPostits < ActiveRecord::Migration[5.0]
def change
add_column :postits, :priority, :integer
end
end
|
class Admin::BooksController < Admin::AdminController
before_action :authorize
before_action :set_book, only: [:show, :edit, :update, :destroy]
# /admin/books
def index
@books = Book.page(params[:page])
@title = admin_title
end
# /admin/books/1
def show
@title = admin_title(@book, [:title, :... |
class CreateCourses < ActiveRecord::Migration[5.0]
def change
create_table :courses do |t|
t.string :title, null: false
t.integer :day, null: false
t.string :time, null: false
t.string :description, null: false
t.string :instructor, null: false
t.date :start_date, null: false
... |
module Efatura
class Configuration
attr_accessor :nif, :password
# SET THE CONFIGURATION INITIALIZER WITH NIL VALUES SINCE THIS INFORMATION
# WILL COME FROM THE GEM USER
def initialize
@nif = nil
@password = nil
end
end
end
|
require 'digest/sha2'
class User < ActiveRecord::Base
validates :username, :presence => true, :uniqueness => true
validates :first_name, :last_name, :presence => true
def generate_codes!
update_attribute(:confirmation_code, generate_confirmation_code)
update_attribute(:cancelation_code, generate_cancel... |
require 'role_model'
class User
include Mongoid::Document
# Include default devise modules. Others available are:
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable,
:token_authentica... |
require 'test_helper'
class UserTest < ActiveSupport::TestCase
setup do
@user = create_a_user!
end
test "can authenticate a user" do
assert @user.authenticate(@user.password), "password ok"
end
test "will reject invalid passwords" do
assert !@user.authenticate("bad password"), "bad passw... |
require 'factory_girl_rails'
FactoryGirl.define do
factory :parking_pass do
sequence(:pass_number) { |n| "#{n}" }
sequence(:address) { |n| "#{n}" }
price_per_hour 1
sequence(:lat) { |n| "#{n}"}
sequence(:lng) { |n| "#{n}"}
end
end
|
class StudentsController < ApplicationController
layout "students"
before_action :require_login
def index
@usage = Usage.find_by(:name=>'StudentUsage')
end
def profile
@user.student_profile ||= StudentProfile.new(preliminary_exam_subject: "N/A",
preli... |
require 'bcrypt'
class User
include DataMapper::Resource
attr_reader :password
attr_accessor :password_confirmation
validates_confirmation_of :password
property :id, Serial
property :username, String, unique: true, required: true
property :password_hash, Text
has n, :projectIdeas
# Hmm.. how to d... |
require 'spec_helper'
describe "catalog/index.html.erb", type: :feature do
let(:user) { FactoryGirl.create(:user) }
before do
@routes = Sufia::Engine.routes
AlertMessage.destroy_all
login_as user
end
after { Warden.test_reset! }
context "alert message" do
let(:alert_message) { "This is a t... |
# encoding: utf-8
class Article < ActiveRecord::Base
belongs_to :first_forum,:class_name =>"Forum"
belongs_to :forum
belongs_to :father_forum,:class_name=>"Forum",:foreign_key => "first_forum_id"
validates_presence_of :title,:message => "标题不为空"
validates_presence_of :context,:message => "正文不为空"
belongs_to :user
belong... |
class AddColumnsOnInsurance < ActiveRecord::Migration
def change
add_column :insurances, :minimum_age, :integer
add_column :insurances, :maximum_age, :integer
add_column :insurances, :group, :string
end
end
|
require './dictionary.rb'
require './player.rb'
class Game
DICTIONARY_FILE_PATH = 'dictionary.txt'
def initialize(*player_names)
@dictionary = Dictionary.new(DICTIONARY_FILE_PATH)
@players = player_names.map { |player_name| Player.new(player_name) }
@losses = @players.reduce({}) { |hash, player| hash.... |
require 'rails_helper'
RSpec.describe FoodItem, type: :model do
subject { FoodItem.new(
name: "Cookies", quantity: 15, section_id: 1, brand_id: 1)}
describe "Validations" do
it { should validate_presence_of(:name) }
it { should validate_uniqueness_of(:name) }
it { should validate_presen... |
# frozen_string_literal: true
# rubocop:disable Style/EvalWithLocation
module Kernel
# Captures the given stream and returns it:
#
# @param [String] stream
#
# The name of the stream to be captured
#
# @example Capture output
#
# stream = capture(:stdout) { puts 'notice' }
# stream # => "not... |
class LinkMailer < ActionMailer::Base
default :from => 'onetimelink@gmail.com'
def email_link(link)
@link = link
mail :to => @link.email, :subject => "Someone sent you a link!"
end
end
|
class MediaMedia < ActiveRecord::Base
belongs_to :media_gallery, inverse_of: :media_medias
has_attached_file :file, styles: {medium: "1000x400#", list: "455x325#", thumb: "300x200#"}, default_url: "/assets/medium/missing.png",
:path => ":rails_root/public/:url",
:url => "/sys... |
class SessionsController < ApplicationController
def new
end
def create
@user = User.authenticate user_params[:email], user_params[:password]
if @user
session[:user_id] = @user.id
flash[:success] = "You are now logged in. Welcome and enjoy."
redirect_to root_path
else
flash[:danger] =... |
module Binance
module Client
class REST
METHODS = [
# Public API Methods
# #ping
{ name: :ping, client: :public,
action: :get, endpoint: :ping },
# #time
{ name: :time, client: :public,
action: :get, endpoint: :time },
# #exchange_info
... |
class CreateHistories < ActiveRecord::Migration[5.2]
def change
create_table :histories do |t|
t.belongs_to :company, foreign_key: true
t.belongs_to :department, foreign_key: true
t.belongs_to :user, foreign_key: true
t.integer :users
t.string :history
t.timestamps
end
end
end |
FactoryGirl.define do
factory :teacher do
first_name "Mr"
last_name "Garrison"
subject "History"
end
end |
# frozen_string_literal: true
class CreateAgendas < ActiveRecord::Migration
def change
create_table :agendas do |t|
t.references :academic_degree_term
t.string :token
t.integer :courses_per_schedule
t.text :courses
t.text :leaves
t.timestamps
end
add_index :agendas, :... |
Pod::Spec.new do |s|
s.name = 'RepoYBTest'
s.version = '1.0.1'
s.summary = 'An easy way to use pull-to-refresh'
s.homepage = 'https://github.com/onelibra/RepoYBTest'
s.license = 'MIT'
s.authors = {'yangbo' => 'yangbo@zgjyjx.com'}
s.platform = :ios, '8.0'
s.source = {:git => 'ht... |
# frozen_string_literal: true
require_relative 'lib/task'
namespace :populate do
desc 'Populate you viky with dummy agent for performance tests'
task :agents, %i[email nb_agents] => [:environment] do |_t, args|
user = User.find_by_email(args[:email])
opts = {
owner: user,
nb_interpretation: 1... |
# -*- coding: utf-8 -*-
=begin
Uma grande emissora de televisão quer fazer uma enquete entre os seus
telespectadores para saber qual o melhor jogador após cada jogo. Para isto, faz-se
necessário o desenvolvimento de um programa, que será utilizado pelas
telefonistas, para a computação dos votos. Sua equipe foi contrat... |
class FixColumnAttendanceColumnName < ActiveRecord::Migration[5.2]
def change
rename_column :event_attendances, :user_id, :attendee_id
rename_column :event_attendances, :event_id, :attended_event_id
end
end
|
Given(/^I am on the Base logging page$/) do
visit_page(LoginPage)
@current_page.wait_for_loading_elements
end
When(/^I Log into the Web version of Base$/) do
on_page(LoginPage).log_in
end
And(/^Create a new Lead$/) do
on_page(LeadsPage).goto_leads
@current_page.skip_intro #This is needed since while using W... |
class Action
def initialize
@is_loaded = false
end
def load
unless loaded?
@is_loaded = true
yield if block_given?
else
raise "cannot load action twice"
end
end
def loaded?
@is_loaded
end
end
|
control "M-2.8" do
title "2.8 Enable user namespace support (Scored)"
desc "
Enable user namespace support in Docker daemon to utilize container user to
host user remapping. This recommendation is beneficial where containers you are
using do not have an
explicit container user defined in the container imag... |
require_relative '../../automated_init'
context "Output" do
context "Summary" do
context "Enter File" do
output = Output.new
path = Controls::Path.example
output.file_count = 11
output.enter_file(path)
test "File count is incremented" do
assert(output.file_count == 12)
... |
class QuantityValidator < ActiveModel::Validator
def validate(record)
if record.deal.quantity_available > 0
qty_can_be_purchased = record.user.qty_can_be_purchased(record.deal)
qty_allowed = qty_can_be_purchased - record.quantity
if qty_allowed < 0
record.errors.add(:base, "Max. limit ex... |
class UserGrid
include Datagrid
scope do
User.order("id DESC")
end
filter(:id, :string)
filter(:fio, :string){ |value| where('fio ILIKE ?', "%#{value}%") }
filter(:email, :string){ |value| where('email ILIKE ?', "%#{value}%") }
end
|
class Usertest < ActiveRecord::Base
belongs_to :user
has_many :comments
mount_uploader :picture, PictureUploader
end
|
class AppsController < ApplicationController
before_action :set_app, only: [:show, :update, :destroy]
# GET /apps
def index
@apps = App.all
@apps = @apps.map do |hash|
{ name: hash[:name], token: hash[:token] }
end
json_response(@apps)
end
# POST /apps
def create
# print(app_pa... |
module Scrabble
class Player
attr_accessor :name, :plays
def initialize(name)
@name = name
@plays = []
@bag = nil
@current_tiles = []
end
def won?
if total_score >= 100
return true
else
return false
end
end
def play(word)
if won?
false
else
@plays.push(word.do... |
require 'DockingStation'
describe DockingStation do
describe '#dock' do
it 'raises an error when station is full' do
#Arrange
station = DockingStation.new
bike = Bike.new
#act
station.capacity.times { station.dock(bike) }
#assert
expect { station.dock(bike) }.to... |
class DeductionDetailsController < ApplicationController
before_action :set_deduction_detail, only: [:show, :edit, :update, :destroy]
# GET /deduction_details
# GET /deduction_details.json
def index
@deduction_details = DeductionDetail.all
end
# GET /deduction_details/1
# GET /deduction_details/1.js... |
class CreateProperties < ActiveRecord::Migration
def change
create_table :properties do |t|
t.string :name
t.string :title
t.string :summary
t.jsonb :data
t.integer :unit_id
t.string :unit_type
t.string :prop_type
t.timestamps null: false
end
end
end
|
require 'spec_helper'
describe "charities/index" do
let(:charities) { create_list(:charity, 4) }
before do
assign(:charities, charities)
end
describe "a merchant is set" do
let(:merchant) { create(:merchant) }
before do
assign(:merchant, merchant)
render
end
it "has a gri... |
require 'digest/md5'
class TickerLine < ActiveRecord::Base
belongs_to :ticker
def hash
Digest::MD5.hexdigest("jabber-ticker##{to_s}")
end
def known?(tl)
TickerLine.find_by_hash(tl.hash).empty?
end
def to_s
"#{date}: #{text}"
end
end
|
require "spec_helper"
describe ReminderMailer do
include ActionView::Helpers::DateHelper
let(:organizer) { FactoryGirl.create(:user) }
let(:invitee1) { FactoryGirl.create(:user) }
let(:invitee2) { FactoryGirl.create(:user) }
let(:event) { FactoryGirl.create(:event, :organizer=> organizer) }
befo... |
class PersonalWatchlistsController < ApplicationController
# GET /personal_watchlists
def index
@personal_watchlist = PersonalWatchlist.all
render json: @personal_watchlist
end
# GET /personal_watchlists/:id(.:format)
def show
@personal_watchlist = PersonalWatchlist.... |
require 'spec_helper'
require 'webmock/rspec'
describe Space, 'callbacks' do
it 'sets the name on create' do
space = Space.new(url: 'https://www.cobot.me/api/spaces/co-up')
space.run_callbacks :create
expect(space.name).to eq('co-up')
end
end
describe Space, '#to_param' do
it 'returns the name' do
... |
class RemotePhoto
attr_accessor :id, :title, :source_url, :source_created_at, :thumbnail_url, :thumbnails
end |
FactoryBot.define do
factory :attachment do
encryption_key do
Base64.strict_encode64(
"\xA1\xF3\x10\xC6\x04$\xDD\xEE\xDAV\x9EM9\x99<ipr\x10yzk\xEE\xF1#\xDF\x8E\xE2j\xEC\xB2\x8B"
)
end
encryption_iv do
Base64.strict_encode64(
"\xCA\fH\xFC\xBE;[IZ[/\"{\xC7\xD8\xF4"
)
... |
class ChoiceGenerator
def initialize(user_input)
@choice = user_input
end
def generate_choice
Write your code here to generate choice
end
end |
class Age
def self.now(dob)
new(dob).now
end
def initialize(dob)
@dob = dob
end
def now
at Time.now
end
def at(date)
(f(date) - f(@dob)) / 10000
end
private
def f(date)
date.strftime('%Y%m%d').to_i
end
end
|
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
post :operation, to: 'main#operation'
mount ActionCable.server, at: '/cable'
end
|
# frozen_string_literal: true
class DocumentsController < ApplicationController
DEFAULT_PER_PAGE = 10
DEFAULT_PAGE_NUMBER = 1
# search
def index
docs = available_documents
docs = docs.tagged_with(params[:tags], search_type: search_type) if params[:tags].present?
docs = docs.paginate(per_page, page_... |
require './lib/player'
class CPUPlayer < Player
def place_ships
ships.each { |ship| cpu_place_ship(ship) }
end
def determine_placement_coords(ship, horizontal)
x1 = x2 = Array(0..grid_size - ship.size).sample
y1 = Array(0..grid_size - ship.size).sample
y2 = y1 + ship.size - 1
x1, y1 = y1, x1... |
require 'rails_helper'
RSpec.describe "vouchers/index", type: :view do
before(:each) do
assign(:vouchers, [
Voucher.create!(
:theater => nil,
:theater_screen => nil,
:name => "Name",
:description => "Description",
:price => "9.99",
:is_deleted => false
... |
# source: https://launchschool.com/exercises/997ac42a
# Q: Write a program that will take a decimal number, and convert it to the
# appropriate sequence of events for a secret handshake.
class SecretHandshake
def initialize(val)
@seed = valid_int?(val) && valid_binary?(val) ? val.to_i : 0
end
def commands
... |
require 'projenitor/template/manifest_runner'
require 'projenitor/template/file_handler'
require 'projenitor/template/erb_runner'
require 'projenitor/template/project'
require 'projenitor/template/file_mapping'
require 'projenitor/template/dir_mapping'
require 'projenitor/template/generated_file'
require 'projenitor/te... |
class Example < ActiveRecord::Base
belongs_to :user
has_many :example_signs, :dependent => :destroy
has_many :signs, :through => :example_signs
has_many :measure_values, :through => :example_signs
end
|
Vagrant.configure("2") do |config|
# hypervisor
config.vm.provider "virtualbox" do |vmp|
vmp.memory = 4096
vmp.cpus = 2
end
# base OS
config.vm.box = "generic/centos7"
# machine specific
config.vm.hostname = "single.vagrant"
config.vm.network "private_network", ip: "192.168.23.30"
# run ins... |
require "test_helper"
class ArticlesControllerTest < ActionDispatch::IntegrationTest
include ApiGuard::Test::ControllerHelper
setup do
@tokens = jwt_and_refresh_token(users(:one), 'user')
@headers = { Authorization: 'Bearer ' + @tokens[0].to_s }
@article = articles(:one)
end
test "should get ind... |
module RPL
# The main interpreter class.
class Sequencer
attr_reader :stack, :names
# No arguments -- creates a "clean slate" interpreter.
def initialize
@parser = Parser.new
@walker = Walker.new
@stack = []
@names = {}
self.wordsize = 0
end
#
# Compile a c... |
require "rails/generators"
module AccountAuthentication
module Generators
class InstallGenerator < Rails::Generators::Base
source_root File.expand_path('../install/templates', __FILE__)
def add_account_authentication_initializer
path = "#{Rails.root}/config/initializers/account_authentication.rb"
... |
FactoryGirl.define do
factory :service, aliases: [:service_created_by_sparc] do
organization factory: :organization_core
sequence(:name) { Faker::Commerce.product_name }
description 'Description'
abbreviation 'Abbreviation'
one_time_fee false
is_available true
after(:create) do |service|... |
# The MIT License (MIT)
#
# Copyright (c) 2013 Andreas Schmidt
#
# 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
# to use, copy, m... |
json.array!(@daily_menus) do |daily_menu|
json.extract! daily_menu, :id, :body, :message
json.url daily_menu_url(daily_menu, format: :json)
end
|
class CreateDatosImportados < ActiveRecord::Migration
def change
create_table :datos_importados do |t|
t.string :artista
t.date :fecha
t.time :horario
t.string :lugar
t.string :direccion1
t.string :barrio1
t.string :web1
t.string :mail1
t.string :telefono1
... |
require 'ascii_toons/version'
require 'ascii_toons/art'
module ASCIIToons
def self.register(name, template)
ASCIIToons.const_set name, ASCIIToons::Art.new(template)
end
DEFAULT_TEMPLATE_PATH = File.expand_path('../../templates', __FILE__)
register :Gandalf, File.join(DEFAULT_TEMPLATE_PATH, 'gandalf.t... |
class Doctor < ActiveRecord::Base
belongs_to :patient
has_many :appointments
has_many :patients, through: :appointments
# def doctor_appointment=(doctor)
# self.doctor = Doctor.find_or_create_by(name: doctor.name)
# self.doctor.update(doctor)
# end
end
|
Rails.application.routes.draw do
mount EasyMonitor::Engine => '/easy_monitor'
resources :users
end
|
# frozen_string_literal: true
# Advent of Code 2020
#
# Robert Haines
#
# Public Domain
require 'aoc2020'
module AOC2020
class PassportProcessing < Day
def setup
@input = parse(read_input_file)
end
def part1
valid = @input.count { |passport| valid?(passport) }
puts "Part 1: #{valid}"... |
# (c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
# question 1
# numbers = [1, 2, 2, 3]
# numbers.uniq
# puts numbers
# I would expect the array [1,2,2,3] because #uniq didn't mutate the array
# Correction: the numbers are listed as 1 2 2 3 (on individual lines) because of the puts method
# question 2
# ! can be used both to create a "not" operator ... |
# == Schema Information
#
# Table name: pictures
#
# id :integer not null, primary key
# title :string(255) default("*")
# description :text
# user_id :integer not null
# created_at :datetime
# updated_at :datetime
#... |
#! /usr/bin/env ruby
require 'json'
# This script attempts to identify any facts that create facts with dots in their names.
problems = []
Dir.glob('lib/facter/*').each do |fact|
next unless File.file? fact
if File.read(fact) =~ /Facter\.add.*\..* [do|{]/
problems << [ "#{ENV['mvp_owner']}-#{ENV['mvp_name']}-... |
class CreateCalendarEventsWeekDays < ActiveRecord::Migration
def change
create_table :calendar_events_weekdays, id: false do |t|
t.references :calendar_event, index: true, foreign_key: true
t.references :weekday, index: true, foreign_key: true
t.timestamps null: false
end
end
end
|
class AuditProblem::MissingPageRange < AuditProblem::EntrySpecific
MIN_PAGE_RANGE = 10
field :num_pages, :type => Integer
field :starting_page, :type => Integer
field :ending_page, :type => Integer
def self.run(options = {})
problems = []
Entry.connection.execute("SET @prior_end_page = 0")
entri... |
FactoryGirl.define do
factory :setting do
daq_controller_host "localhost"
daq_controller_port "8011"
api_key "development"
end
end
|
# frozen_string_literal: true
Rails.application.routes.draw do
resources :body_scales, param: :date, only: %i(index show update)
match '*path', to: 'application#handle_no_route_matches', via: :all
end
|
namespace :data do
task :load_translations, [:locale] => [:environment] do |t, args|
locale = args['locale']
file = [locale, 'yml'].join('.')
translations = YAML.load_file(Rails.root.join('config/locales', file))[locale]
I18n.backend.store_translations(locale, translations, :escape => false)
end
en... |
shared_examples_for "TroleGroup Write API" do
describe '#clear_rolegroups!' do
it "should clear rolegroups and invalidate rolegroups cache" do
user.set_rolegroups :admin
user.clear_rolegroups!
expect { user.rolegroup_list }.to change{user.rolegroup_list_value }
user.rolegroup_list.should ... |
class User < ActiveRecord::Base
has_many :projects
has_many :assignments
has_many :assigned_projects, through: :assignments, source: :project
has_many :comments
has_many :commented_projects, through: :comments, source: :project
# what I'd really like to be able to do
# has_many :associated_projects, throu... |
class BuildMediaShareResqueQueue
QUEUE_NAME = :build_media_share_resque_queue
@queue = QUEUE_NAME
def self.enqueue(rule_id)
Resque.enqueue(BuildMediaShareResqueQueue, rule_id)
end
def self.perform(rule_id)
MediaShareRule.find(rule_id).build_share
end
end
|
require_relative 'common'
class Logic
def initialize(site, logger)
@site = site
@log = logger
@crawler = BaseCrawler.factory(@site)
@parser = BaseParser.factory(@site)
@formatter = Formatter.new(@log)
end
def crawl(location,request)# main処理:クローリング〜DB格納
page_num = 1
begin
hash_r... |
class Shift < ApplicationRecord
has_and_belongs_to_many :workers
end
|
#Just like how we've built reader methods that expose the value of
#instance variables, we need to build a method that will expose,
#or make accessible outside of the class, the value of a class variable.
class Dog
attr_accessor :name
@@all = Array.new
def initialize(name)
@name = name
@@all << self
end
def s... |
class BrandsController < ApplicationController
before_action :set_image, :only => [:edit,:update,:destroy]
before_filter :authorize, :except =>[:index]
def set_image
@image = Brand.find(params[:id])
end
def index
@image = Brand.all
@banner = Poster.where(:type => "Banner")
end
def new
@brand = Brand.new
... |
# spec/features/auth_spec.rb
require 'rails_helper'
require 'spec_helper'
feature "the signup process" do
username = create_user
scenario "has a new user page" do
visit new_user_url
expect(page).to have_content "New User"
end
feature "signing up a user" do
before(:each) do
sign_up_user(usern... |
class Order < ActiveRecord::Base
belongs_to :user
has_many :cart_items
validates_presence_of :address_id, :message => "Please select a delivery address"
validates_presence_of :delivery_id, :message => "Please select a delivery method"
def delivery_taxes
if delivery_id.nil?
Delivery.first.deli... |
require_relative '../request_spec_helper'
describe Playercenter::Backend::API do
describe "Avatar retrieval" do
describe "on facebook" do
it "redirects to the facebook avatar endpoint" do
facebook_id = '768942708'
token = connection.auth.venue_token(app_token, 'facebook', 'name' => 'Peter S... |
class CreateMyAvatars < ActiveRecord::Migration
def change
create_table :my_avatars do |t|
t.integer :health_xp
t.integer :stamina_xp
t.integer :strength_xp
t.integer :intelligence
t.integer :user_id
t.timestamps null: false
end
add_index :my_avatars, :user_id
end
... |
FactoryGirl.define do
factory :creatures do
landscape_id { rand(1..10) }
name { ["Test Creature 1", "Test Creature 2", "Test Creature 3"].sample }
type { ["Beast", "Humanoid", "Celestial", "Fiend"].sample }
size { ["Small", "Medium", "Large"].sample }
stren... |
# The basic idea is that I am creating a MenuStrip that is reusable, and can be called directly from any page that inherits it.
# Not your classic "IS-A" relationship, but it does encourage re-use of code.
class AdminEditCustomerPage < AdminMenuStrip
def initialize(browser)
@browser=browser
Watir::Wait.until {... |
class Review < ActiveRecord::Base
belongs_to :product
belongs_to :user
validates :product_id, presence: true
validates :user_id, presence: true
validates :rating, presence: true
validates :comment, presence: true
def blank_stars
5 - rating.to_i
end
end
|
class NurseAssignment < ApplicationRecord
belongs_to :patient
belongs_to :nurse
validate :start_date_valid?
def start_date_valid?
if !start_date.is_a?(Date) || start_date > Time.now
errors.add(:start_date, 'must be valid date and must be in the past')
end
end
end
|
module PageRedirect
VERSION = "0.2.0"
AUTHORS = ["Michael Haag"]
EMAIL = ["michael.haag@ahorngmbh.de"]
HOMEPAGE = "http://ahorngmbh.de"
DESCRIPTION = "Radiant CMS extension"
SUMMARY = "A redirect page will redirect to the url defined in the first page part.
This allows you... |
# Rails.application.routes.draw do
# devise_for :users
# root "groups#index"
# resources :users, only: [:index, :edit, :update]
# resources :groups, only: [:new, :create, :edit, :update] do
# resources :messages, only: [:index, :create]
# end
# end
# messagesのルーティングはgroupsにネストされているため、
# group_idを含んだパスを生成... |
class PostForm
ValidationError = Class.new(StandardError)
include Virtus.model
include ActiveModel::Conversion
include ActiveModel::Validations
attribute :id, Integer
attribute :title, String
attribute :content, String
attribute :category_id, Integer
attribute :position, Integer, :default=>-1
attr... |
default_run_options[:pty] = true
#ssh_options[:forward_agent] = true
# Overwrite the default deploy start/stop/restart actions with passenger ones
require 'config/deploy/passenger'
require 'bundler'
set :repository, "git@github.com:LRDesign/test-r3.git"
# set :deploy_via,... |
# frozen_string_literal: true
# Takes a string or variable and capitalizes the first letter of every word.
# {{ string | capitalize_all }}
module CapitalizeWords
def capitalize_all(words)
words.to_s.split(' ').map(&:capitalize).join(' ')
end
end
Liquid::Template.register_filter(CapitalizeWords) |
require "spec_helper"
describe "include node" do
def build_include_node
XPain::Builder.new do |xsd|
xsd.schema do
xsd.include "more.xsd"
end
end
end
it "should create a include node" do
schema = build_include_node
schema.doc.xpath("//xsd:include").size.should == 1
end
i... |
require "./LexicalAnalyzer/print"
class Lexer
def initialize(file_name)
@file = file_name
end
def parser
white_space = [32, 13, 12, 11, 10, 9]
digits = (48..57).to_a
chars = (65..90).to_a
separators = ($SEPARATORS_TOKENS.keys).to_a
key_words = ($KEY_WORDS_TOKENS.keys).to_a
@lex_list ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.