text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
module Bolt
class Secret
class Base
def hooks
%i[resolve_reference secret_encrypt secret_decrypt secret_createkeys validate_resolve_reference]
end
def encode(raw)
coded = Base64.encode64(raw).strip
"ENC[#{name.upcase},#{coded}]"
end
... |
require 'rails_helper'
include Warden::Test::Helpers
RSpec.describe "Group::Conversations", type: :request do
let(:creator) { create(:user) }
let(:name) { "Hotwire and Rails" }
let(:conversation) {create(:group_conversation, name: name)}
context 'non-signed-in user' do
it 'GET :index redirects to login pa... |
puts "Salut, ça farte ?"
#begin Le programme hello.rb a eu l'erreur suivante ligne 1"unterminated string# meets end of file".Cela veut dire qu'un string non fini a rencontré une fin de# ligne
|
class ChangeItemValueToInteger < ActiveRecord::Migration[5.2]
def self.up
change_column :items, :value, :integer, default: 0
end
def self.down
change_column :items, :value, :decimal, precision: 5, scale: 2, default: 0
end
end
|
# Pair commits provide name and email but no username.
# Regular commits provide all three.
# Comment webhooks only include a username, no email or name.
class Author < ActiveRecord::Base
validate :has_at_least_one_property
def self.create_or_update_from_payload(payload)
CreateOrUpdateFromPayload.call(payload... |
require "spec_helper"
require "rspec_api_documentation/dsl"
resource "Managing the members of a project" do
let(:friend_one) { create(:user) }
let(:friend_two) { create(:user) }
let(:user) { create(:user).with_friend(friend_one).with_friend(friend_two) }
let(:project) { create(:project, user: user).with_member... |
Rails.application.routes.draw do
root to: 'choices#index'
resources :choices do
resources :comments
end
end
|
class AddDefaultTrueToAttendancesStatus < ActiveRecord::Migration
def change
change_column :attendances, :status, :boolean, :default => true
end
end
|
require 'spec_helper'
describe "watch_sites/new" do
before(:each) do
assign(:watch_site, stub_model(WatchSite,
:name => "MyString",
:team => nil,
:venue => nil
).as_new_record)
end
it "renders new watch_site form" do
Team.should_receive(:all).at_least(1).times.and_return([])
Ve... |
module WordSearch
class SuffixArrayReader
DEFAULT_OPTIONS = {
:path => nil,
:io => nil,
}
attr_reader :block_size, :inline_suffixes, :inline_suffix_size
def initialize(doc_map, options = {})
options = DEFAULT_OPTIONS.merge(options)
@doc_map = doc_map
... |
class HTML
def self.tag(tag, content, attributes={})
%Q(<#{tag} #{extract(attributes)}>#{content}</#{tag}>)
end
private
def self.extract(attributes)
attributes.inject("") do |attrs, (attr,value)|
attrs<< " "if attrs != ""
attrs<< %(#{attr}="#{value}")
end
end
end
|
require 'pry'
class Player
def initialize(**params)
end
def select_num
while true
print "番号を選択して下さい > "
select_num = gets.to_i
break if(1..9).include?(select_num)
puts "1~9の番号で選択して下さい。"
end
tables = tables.flatten
tables[select_num - 1] = "○"
tables = [tables[0..... |
# encoding: UTF-8
module API
module Helpers
module V1
module AlbumsHelpers
extend Grape::API::Helpers
def serialized_album(user, options={})
options = { serializer: :album }.merge(options)
serialized_object(user, options)
end
end
end
end
end
|
class InvestmentsController < ApplicationController
before_action :set_investment, only: [:show, :edit, :update, :destroy]
skip_before_action :verify_authenticity_token
# GET /accounts
# GET /accounts.json
def index
@accounts = Account.where(user_id: current_user.id)
@investments = Investment.where(a... |
require_relative "occupant"
class Box
attr_reader :owner
def initialize(owner = Occupant.new(first_name, last_name))
@owner = owner
end
end
|
require 'spec_helper'
describe 'yum_harden::create_mirror_repo', :type => :define do
let(:title) { 'atomic' }
let(:params) {
{
:repo_name => 'atomic',
:yum_server_ip => '1.1.1.1',
}
}
it do
should contain_yumrepo('mirror-atomic').with(
'baseurl' => 'http://1.1.1.1/mirror/atomic',... |
module SoManyFeeds
module Manager::Feeds
extend ActiveSupport::Concern
included do
before '/*-feed*' do
@namespace = 'user'
end
get '/my-feeds' do
require_login
respond :my_feeds
end
post '/my-feeds/:id' do
require_login
id = par... |
class MainController < UIViewController
def viewDidLoad
super
self.title = 'BergenRB Events'
@table = UITableView.alloc.initWithFrame(self.view.bounds)
@table.dataSource = self
self.view.addSubview(@table)
@data = []
Event.all do |events|
@data = events
@table.reloadData
... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'hypgen/version'
Gem::Specification.new do |spec|
spec.name = 'hypgen'
spec.version = Hypgen::VERSION
spec.authors = [
'Marek Kasztelnik',
... |
# frozen_string_literal: true
class Location::Prayer < ApplicationRecord
belongs_to :location
has_one_attached :banner
validates :name, :snippet, :content, presence: true
validates :banner,
attached: true,
aspect_ratio: :is_16_9,
content_type: %r{\Aimage/.*\z},
d... |
# frozen_string_literal: true
class InvalidRequest < StandardError
attr_reader :message, :status
def initialize(message = nil, status = nil)
@message = message || "Oops... Something Went Wrong!"
@status = status || :bad_request
end
end
|
require 'spec_helper'
describe Contact do
it { should validate_presence_of(:user_id) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:title) }
it { should validate_presence_of(:email) }
it {should belong_to :user}
it {should have_many(:goals).dependent(:destroy)}
it "has... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
resources :customers, only: :index do
get 'download', on: :collection
get 'error'#, on: :collection
end
end
|
# frozen_string_literal: true
require "digest"
class FetchMohfw < BaseCommand
def self.perform_task
new.call_with_transaction
end
attr_reader :response, :raw_patients, :unknown_districts
def run
@unknown_districts = {}
log(:yellow, "Starting job #{run_id}")
result = fetch &&
cre... |
require 'rails_helper'
RSpec.describe Ride, type: :model do
describe 'relationships' do
it { should have_many :mechanic_rides}
it { should have_many(:mechanics).through(:mechanic_rides)}
end
# describe 'instance methods' do
# it '#average_price_of_snacks' do
# owner1 = Owner.create(name: 'Tomm... |
include_recipe 'torque::default'
include_recipe 'nfs::client4'
if Chef::Config[:solo]
head = node
else
heads = search(:node,
'role:torque-server',
filter_result: { name: ['hostname'],
ip: ['ipaddress']
}
... |
module Jekyll
module FullTextSearchFilter
def full_text_search(input)
sanitized = input.gsub(/[^0-9a-z\'’\s]/, '')
words = sanitized.split(" ")
words.join(" ")
end
end
end
Liquid::Template.register_filter(Jekyll::FullTextSearchFilter)
|
class Msg::BaseService < CommonService
class << self
def send_msg(user_id, friend_id, content)
return failure(code: 1, message: 'not friend') unless UserRelation.exists?(user_id: user_id, friend_id: friend_id)
attrs = {user_id: user_id, friend_id: friend_id, sender_id: user_id, reciever_id: friend_id,... |
# frozen_string_literal: true
require "beyond_api/utils"
module BeyondApi
autoload :ShopAddress, "beyond_api/resources/shops/address"
autoload :ShopAttributes, "beyond_api/resources/shops/attributes"
autoload :ShopImages, "beyond_api/resources/shops/images"
autoload :ShopLegals, "beyond_api/resourc... |
class AddBrandToCodes < ActiveRecord::Migration
def self.up
add_column :codes, :car_brand, :text #you can change the name, see wiki
end
def self.down
remove_column :car_brand, :codes
end
end
|
class CreateMatchTimeProposals < ActiveRecord::Migration
def change
create_table :match_time_proposals do |t|
t.references :match
t.references :team
t.datetime :proposal
t.timestamps
end
add_index :match_time_proposals, :match_id
add_index :match_time_proposals, :team_id
end... |
# 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 rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
require 'rails_helper'
RSpec.describe "games/show", type: :view do
before(:each) do
@game = assign(:game, Game.create!(
:player_card => "Player Card",
:dealer_card => "Dealer Card",
:winner => "Winner",
:simulation => nil
))
end
it "renders attributes in <p>" do
render
ex... |
class Instructor < ApplicationRecord
has_one :cohort
# validates_numericality_of :age, :in => 1..150
# validates :salary, numericality: { other_than: 0 }
validates :age, inclusion: { in: 1..150 }
validates :salary, numericality: { other_than: 0 }
end
|
require 'spec_helper'
describe "Model.find_or_create_by_foo" do
describe "record exists" do
before do
@article = Article.create(:title => "FooBar",
:text => "Original text")
end
it 'should find it' do
article = Article.find_or_create_by_title(:title => "FooB... |
# frozen_string_literal: true
class BeerFlavor < ActiveRecord::Base
belongs_to :beer
belongs_to :flavor
end
|
require 'trk_datatables/version'
# modules
require 'trk_datatables/preferences.rb'
require 'trk_datatables/base_helpers'
require 'trk_datatables/base'
require 'trk_datatables/active_record'
require 'trk_datatables/neo4j'
require 'trk_datatables/dt_params'
require 'trk_datatables/column_key_options.rb'
require 'trk_data... |
require 'rubygems'
require 'active_support'
require "test/unit"
require File.dirname(__FILE__) + "/../lib/xml_node"
class TestXmlNode < Test::Unit::TestCase
def test_parse_sanity
assert_raise(ArgumentError) { XmlNode.parse }
assert_nothing_raised { XmlNode.parse('<feed/>') }
end
def test_parse_... |
class Delete < ActiveRecord::Migration
def change
remove_column :itri_records, :property_id
end
end
|
# encoding: utf-8
module Egoi
class ExceptionMessage
def initialize(error_code)
@message = self.class.error_messages[error_code]
end
def message
@message
end
def self.error_messages
@error_messages ||= {
"CANNOT_BE_DELETED" => "A campanha é recorrente ou activada por e... |
class ApplyjobsController < ApplicationController
before_action :set_applyjob, only: [:show, :edit, :update, :destroy]
# GET /applyjobs
# GET /applyjobs.json
def index
@applyjobs = Applyjob.all
end
# GET /applyjobs/1
# GET /applyjobs/1.json
def show
end
# GET /applyjobs/new
def new
@app... |
FactoryBot.define do
factory :alert do
text 'hello'
permalink 'http://example.com/123'
user_permalink 'http://example.com/user-123'
end
end
|
class BingResultsPage
include PageMixIn
attr_accessor :results, :conversion_result
def initialize(browser)
@browser = browser
@results = @browser.span(:id => "count")
@conversion_result = @browser.span(:class => "sc_bigLine")
super
end
def number_search_results
result = /^[\s\w-]* of ([... |
require 'fileutils'
module Helpers
def delete_files(file_names)
if file_names.nil? || file_names=='' || file_names.empty?
raise ArgumentError, "file_names is either empty or contains no values"
end
if file_names.is_a ? Array
file_names.each { |f|
path = File.join(Dir.pwd,name)
File.delete(path) ... |
require "taylor-swift/query"
require "taylor-swift/utils"
require "taylor-swift/settings"
module TaylorSwift
class << self; attr_accessor :redis end
StorageDeliminator = ":"
ValidResourceTypes = [:items, :tags, :users]
# These are instance methods that get included on all 3 models.
#
module Base
... |
module Formotion
module RowType
class PickerWithDoneRow < PickerRow
include RowType::ItemsMapper
def after_build(cell)
super
keyboardDoneButtonView = UIToolbar.new
keyboardDoneButtonView.barStyle = UIBarStyleBlack
keyboardDoneButtonView.translucent = tru... |
MRuby::Gem::Specification.new('mruby-print') do |spec|
spec.license = 'MIT'
spec.author = 'Jun Takeda'
spec.summary = 'standard print/puts/p for mruby-arduino environments'
spec.description = 'Redirecting print/puts/p to Arduino Serial.This gem is intended to be compatible with standard mruby-print.'
spec.a... |
require 'rails_helper'
RSpec.describe Event, type: :model do
describe 'relationships' do
it { should belong_to :calendar }
it { should have_one(:company).through(:calendar) }
end
describe 'validations' do
subject { FactoryGirl.build(:event) }
it { should validate_presence_of :client_email }
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Configure The Box
config.vm.box = "precise32"
config.vm.hostname = "homestead"
# Don't Replace The D... |
require 'spec_helper'
bool_options = [true, false]
describe 'secure_linux_cis::redhat7::cis_5_4_1_4' do
on_supported_os.each do |os, os_facts|
bool_options.each do |option|
context "on #{os}" do
let(:facts) { os_facts }
let(:params) { { 'enforced' => option, 'pass_inactive_days' => 30 } }
... |
RSpec.describe 'the brooms in the BroomCloset' do
describe 'blanks_to_nil' do
it 'turns empty strings into nil' do
expect(TinySweeper::BroomCloset.blanks_to_nil('')).to be_nil
end
it 'leaves nil values alone' do
expect(TinySweeper::BroomCloset.blanks_to_nil(nil)).to be_nil
end
it 'leav... |
class MusicConcert < ActiveRecord::Base
has_many :comments
validates :artist, presence: true
validates :venue, presence: true
validates :city, presence: true
validates :date, presence: true
validates :price, presence: true
validates :description, presence: true
validates :price, numericality: true
def self.upcoming_c... |
class ProjectsController < ApplicationController
#before_action :set_project, only: [:show, :edit, :update, :destroy]
#before_action :authenticate_user!, except: [:index, :show]
# GET /al projects
# GET /projects.json
def index
@title = "Project Listing"
@projects = Project.where(:status => nil).or... |
module V1
class Parkings::OutController < ApplicationController
before_action :load_parking
def update
if @parking.paid? && @parking.update_attributes(status: :finished, finished_at: Time.zone.now)
return head :ok
end
head 500
end
private
def load_parking
@parkin... |
fastlane_version "2.89.0"
default_platform :ios
platform :ios do
desc "Build SwiftKit"
lane :build do
spm(
command: "build",
build_path: "./build",
configuration: "release"
)
end
desc "Run Tests"
lane :test do
sh("swift", "test", "--parallel")
end
end
|
require 'rails_helper'
describe 'User requests', type: :request do
let(:user) { create :user, password: 'password-one' }
context 'unauthenticated' do
it 'rejects edits when user unauthenticated' do
get edit_user_registration_path(user)
expect(response.code).to eq '401'
end
end
context 'au... |
require_relative 'tables'
class CodeWord < Table
table_name 'code_words'
column :id
column :word
prep_generic_stmts
def initialize(db_hash)
super(db_hash)
end
def self.valid_code?(code)
code_parts = code.split("-")
words = select_all.map { |w| w.values[1] }
valid = true
code_parts.e... |
# frozen_string_literal: true
require 'spaceship'
require 'json'
import 'FaslaneUpload.rb'
import 'FastfileTest'
import 'BuildTypeFactory.rb'
import 'Enterprise/Types/Client/Client.rb'
import 'Enterprise/Types/Debug/Debug.rb'
import 'Enterprise/Types/Debug/Subtypes/DebugGeneric.rb'
import 'Store/Store.rb'
import 'Bas... |
# frozen_string_literal: true
RSpec.describe ActiveEncryption::Encryptable do
subject(:record) { klass.new }
before do
allow(ActiveEncryption).to receive(:config) do
config = ActiveEncryption::Configuration::Store.new
config.encryption_setting_store =
ActiveEncryption::EncryptionSetting::Y... |
#!/usr/bin/env ruby
# frozen_string_literal: true
require_relative 'knight'
require_relative 'color'
include Color
knight = Knight.new
def print_intro
puts color_text('Welcome To Knights Travails! Find the shortest path between source and destination!',
:yellow)
puts
puts color_text('Enter C... |
module SharedEntitiesHelper
# list of entities that can generate a Shopify Url
SUPPORTED_EXTERNAL_ENTITIES = %w(product customer order variant).inject({}) {|hsh, sym| hsh[sym] = true; hsh}
def link_to_shopify(idmap)
if SUPPORTED_EXTERNAL_ENTITIES[idmap.external_entity.downcase] && !idmap.external_id.blank?
... |
class TaxRate < ActiveRecord::Base
has_and_belongs_to_many :exempted_categories, class_name: "Category"
end
|
class Ad < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
belongs_to :user
validates_presence_of :title, :city, :description, :price, :contact
include PgSearch
pg_search_scope :search, against: [:title, :category, :city],
using: {tsearch: {prefix: true, any_word: true}}
end
|
require 'spec_helper'
describe CollectionNorth do
it 'is valid' do
expect(CollectionNorth).to be_a(Module)
end
it 'is loadable without preloading rails' do
expect { require 'collection_north' }.not_to raise_error
end
end
|
ActiveAdmin.register_page "Dashboard" do
menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }
content title: proc{ I18n.t("active_admin.dashboard") } do
columns do
column do
panel 'Greetings Earthling' do
h1 'Welcome'
h4 'This is your mission control. Use the r... |
# frozen_string_literal: true
class Checklist < ApplicationRecord
validates_with Validators::Base, fields: %i[ticket title]
belongs_to :ticket
has_one :content, as: :ticket_content, dependent: :destroy
has_many :options, class_name: 'ChecklistOption', dependent: :destroy
end
|
RailsAdmin.config do |config|
### Popular gems integration
config.main_app_name = ["SIC - ", "Secretaria de Saúde"]
## == Devise ==
config.authenticate_with do
warden.authenticate! scope: :user
end
config.current_user_method(&:current_user)
config.configure_with(:import) do |config|
config.logging ... |
class BinarySearchTree
attr_reader :score, :movie, :root_node
attr_accessor :left, :right
def initialize
@root_node = nil
end
def insert(new_score, new_movie)
if @root_node.nil?
@root_node = Node.new(new_score, new_movie)
elsif new_score == @score
puts "Error, the rating #{new_score}... |
# a Rack middleware component that enables ActiveRecord query caching
# To use, put "use QueryCaching" in your Sinatra app.
# http://pivotallabs.com/users/alex/blog/articles/1232-basic-ruby-webapp-performance-tuning-rails-or-sinatra-
class QueryCaching
def initialize(app)
@app = app
end
def call(env)
i... |
class HomeController < ApplicationController
def index
@requested_short_id = nil
if params.present? && params[:short_id].present?
@requested_short_id = params[:short_id]
short_url = ShortUrl.find_by_short_id(@requested_short_id)
if short_url.present?
@requested_redirect_url = sho... |
class RostersController < ApplicationController
before_filter :authenticate_user!, :only => [:new, :create, :destroy]
#FIXME kmh we need to not show roster stats unless league does NOT support games???
def new
@title = "New Roster Item"
@teamstat = Teamstat.find_by_id(params[:teamstat_id]) || not_found
... |
require 'spec_helper'
describe Publisher do
it 'has a valid factory' do
FactoryGirl.create(:publisher).should be_valid
end
it 'is invalid without a name' do
FactoryGirl.build(:invalid_name_publisher).should_not be_valid
end
end |
source 'https://rubygems.org'
gem 'rails', '4.1.4'
gem 'pg' # Use postgresql as the database for Active Record
gem 'jbuilder', '~> 2.0' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'puma' # Use puma as the app server
### Assets
# Coffeescript
gem 'coffee-rails', '~> 4.0.0' # Use C... |
# frozen_string_literal: true
module Members
module Dues
def dues
dues_not_payable if @payment.blank?
end
private
def current_user_dues_due?
current_user&.dues_due?
end
def prepare_dues
@payment = Payment.recent.for_user(current_user).first
@payment ||= Payment.create... |
# frozen_string_literal: true
class Location
Error = Class.new(StandardError)
ArgumentError = Class.new(Error)
InvalidRangeError = Class.new(ArgumentError)
attr_reader :latitude, :longitude
def initialize(latitude, longitude)
@latitude = Float(latitude)
@longitude = Float(longitude)
check_range
... |
#sparql_manager.rb
require 'rubygems'
require 'json'
require 'open-uri'
require 'cgi'
require './model/triplet.rb'
# @author Daniel Machado Fernández
# @version 1.0
#
# Manage all SPARQL queries
class SPARQLManager
# Retrieves the ten diseases which have got more cases
#
# @return [Array] filled by Triplets
def ... |
require 'rails_helper'
describe ProxiesController do
let(:user) { create(:user, slug: 'bx') }
let(:target_url) { 'https://api.foo.com' }
let(:target_request_type) { 'get' }
let(:origin) { 'https://attackofthethighbax.com' }
let!(:cors_host1) { create(:cors_host, host: 'localhost:800', proxy: proxy) }
let!(... |
class DashboardController < ApplicationController
def show
@articles = Article.for_dashboard
@article_count = Article.count
@article_word_count = Article.total_word_count
@most_popular_article = Article.most_popular
@comments = Comment.for_dashboard
@comment_cou... |
class Newsletter
def initialize(event)
@event = event
end
def valid?
@event["event"] == "inbound"
end
def token
@token ||= begin
to_email.sub("@newsletters.feedbin.com", "").sub("test-subscribe+", "").sub("subscribe+", "")
end
end
def to_email
@event["msg"]["email"]
end
... |
require_relative 'emoji'
require_relative 'astapor_api_error'
class Response
RESULT = 'resultado'.freeze
ERROR = 'error'.freeze
STATE = 'estado'.freeze
GRADE = 'nota_final'.freeze
BOT_RESPONSES = {
'INSCRIPCION_CREADA' => "Listo! ya estas inscripto #{Emoji.code(:tada)}",
'CUPO_COMPLETO' => "Oups, no ... |
module Secretary
class Version < ActiveRecord::Base
serialize :object_changes
IGNORE = ["id", "created_at", "updated_at", "password_digest"]
belongs_to :versioned, polymorphic: true
belongs_to :user, class_name: Secretary.config.user_class
#---------------
validates_presence_of :versione... |
require 'open-uri'
class ScrapeTitleJob < ActiveJob::Base
queue_as :default
def perform(media_item_id)
media_item = MediaRepository.find(media_item_id)
doc = Nokogiri::HTML(open(media_item.url))
title = doc.xpath('//title/text()')
media_item.scraped_title = title
media_item.save!
end
end
|
module Dictionary
# カテゴライズ
Categorize = {
'悲劇' => '悲劇',
'勝機' => '勝機',
'勧誘' => '勧誘',
'週末' => '週末',
'徹夜' => '徹夜',
'帰宅' => '帰宅',
'寒気' => '寒気',
'部下' => '部下',
'仲間' => '仲間',
'同僚' => '仲間',
'友達' => '仲間',
'親友' => '親友',
'落し物' => '落し物',
'守る' => '守る',
'どっちかわからない' => ... |
require 'spec_helper'
require 'faraday'
require 'json'
RSpec.describe Piebits::BuildSubmitter do
let(:build) {
Piebits::Build.new(timestamp: 13245, commit_sha: 'abc123', ci_build_url: 'http://foo.bar').tap do |b|
b.add_report(report)
end
}
let(:report) { Piebits::Report.new(category: 'ducks', tool_... |
class Attachment < ApplicationRecord
belongs_to :attachable, polymorphic: true
mount_uploader :source, AttachmentUploader
before_save :update_source_attributes
private
def update_source_attributes
if source.present? && source_changed?
self.source_type = source.file.content_type
end
end
end... |
class CreateCreditMemos < ActiveRecord::Migration
def change
create_table :credit_memos do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "c_name"
t.decimal "c_total"
t.string "c_po"
t.string "c_ed... |
class CreateBooks < ActiveRecord::Migration[5.1]
def change
create_table :books do |t|
t.belongs_to :author, index:true
t.integer :user_id
t.datetime :published_at
t.string :abstract
t.integer :noOfPages
t.timestamps
end
end
end
|
require 'active_record'
class ItemOrder < ActiveRecord::Base
belongs_to :item
belongs_to :order
validates_presence_of :item_id, :order_id
end
|
module Api
module V1
class ProductsController < ApplicationController
def index
@products = Product.all
if user_signed_in?
render json: @products
else
render json: {}, status: 401
end
end
end
end
end |
require 'rails_helper'
feature 'user deletes a game', %{
As an authenticated user
I want to delete a pending game with incorrect data
So that loser nerds don't ruin my reputation
Acceptance Criteria
[x] I must be authenticated to delete a pending game
[x] I must be able to delete the game
[x] I mus... |
# encoding: utf-8
module DesignStoryboard
module Export
@storyboard_cols_count = 0
REGEXP_RULE_FOR_FIND_LINK = /
(?:link|url):[[:blank:]]*(?<uri>[\w\_\-]+:\/\/[\S]+)
/xi
REGEXP_RULE_FOR_FIND_LINK_AND_TITLE = /
(?:link|url):[[:blank:]]*(?<uri>[\w\_\-]+:\/\/[\S]+)
[[:blank:]]*\|[[:b... |
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
require 'spec_helper'
describe TwitterCldr::Tokenizers::DateTokenizer do
describe "#tokens" do
it "should tokenize plaintext segments correctly (i.e. Spanish)" do
data_reader = TwitterCldr::DataReaders::DateDataR... |
ActiveAdmin.register Withdrawal do
permit_params :amount, :state, :user_id, :pay_way
end |
class ProfileForm
include ActiveModel::Model
attr_reader :profile
def initialize(profile)
@profile = profile
end
def email
@profile.email
end
def shipping_address
@profile.shipping_address || @profile.build_shipping_address
end
def billing_address
@profile.billing_address || @pro... |
# frozen_string_literal: true
module Ayte
module Chef
module Cookbook
module ElasticSearch
# Module for common methods that should be called during
# resource definition process
module ResourceDefinitionMethods
def define_common_attributes(timeout: 8)
# Cluster... |
class CreateLinkHistories < ActiveRecord::Migration
def change
create_table :link_histories do |t|
t.string :ident_code,:unique=>true,:null => false
t.datetime :action_time,:null => false
t.integer :agent_id,:null => false
t.integer :to_portal_id,:null => false
t.integer :from_portal... |
cities = {
london: {
sights: ["Tower Bridge", "Big Ben", "London Eye"],
restaurants: ["Nobu", "River Cafe", "Hakkasan"],
peak_season: {
season: "summer",
months: (5..8)
}
},
bangkok: {
sights: ["Grand Palace", "Wat Arun", "Jim Thompso... |
require 'roo'
require 'json'
def add_rate_cards_to_suppliers
suppliers = JSON.parse(File.read(get_mc_output_file_path('suppliers_with_service_offerings_and_regional_availability.json')))
suppliers.each { |supplier| supplier['rate_cards'] = [] }
rate_cards_workbook = Roo::Spreadsheet.open(rate_cards_workbook_fil... |
class Cohort < ApplicationRecord
belongs_to :course, optional: true
has_many :students
has_one :instructor
validates(:name, presence: true, uniqueness: {case_sensitive: false})
validates(:start_date, presence: true)
validates(:end_date, presence: true)
end
|
require('minitest/autorun')
require('minitest/rg')
require_relative('../models/gymclass.rb')
class GymClassTest < MiniTest::Test
def setup
options1 = {
'workout_id' => '4',
'start_date' => '10-Dec-2018',
'start_time' => '19.00',
'capacity' => '5',
'peak' => 'true'
}
@gymcl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.