text stringlengths 10 2.61M |
|---|
class HacoGenerator < Rails::Generators::Base
desc "This generator creates files blablabla..."
source_root File.expand_path("../haco/templates", __FILE__)
def create_top_page_controller_file
copy_file "top_controller_template.rb", "app/controllers/top_controller.rb"
end
def create_top_page_view_file
... |
class AddUserIdtoUsersGenres < ActiveRecord::Migration[5.2]
def change
add_reference :users_genres, :user, foreign_key: true
end
end
|
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_and_belongs_to_many :sites
has_one :setting
enum role: [:user, :distadmin, :inventory, :intersession, :manager,
:accounting, :bidadmin, :biduser, ... |
class JukeboxList < ApplicationRecord
belongs_to :user
has_many :jukebox_list_songs
has_many :songs, through: :jukebox_list_songs
end
|
require 'spec_helper'
describe BaristaMatic::RecipeIngredient do
subject { described_class.new("coffee", 3)}
let(:ingredients_costs){ {"coffee" => "0.50"} }
before :each do
described_class.stub(:ingredients_costs).and_return(ingredients_costs)
end
it 'has a cost' do
expect(subject.cost).to eql("1.... |
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :fan
validates :body, presence: true
validates :commentable, presence: true
validates :fan, presence: true
end
|
class Word < ActiveRecord::Base
validates :name, :presence => true,
:uniqueness => true
has_many :meanings
def to_param
name
end
def self.get(name) # trzeba użyć self., bo get to ma być metoda klasy, a nie obiektu
find_by_name(name) #|| raise ActiveRecord::RecordNotFound
... |
class TicketsController < ApplicationController
before_action :authenticate_user!
before_action :confirmed_user
before_action :admin_user, except: [:create,:destroy,:new,:show]
PER = 5
def index
@info = Information.find(params[:information_id])
@tickets = @info.tickets.page(params[:page]).per(PER).a... |
# frozen_string_literal: true
class OrderAccessory < ApplicationRecord
validates :order_id_fk, :accessory_id_fk, :purchase_price, presence: true
end
|
class CustomGatewaysController < ApplicationController
before_filter :login_required
filter_access_to :all
def index
@gateways = CustomGateway.available_gateways
@own_gateways = CustomGateway.own_gateways
#@own_gateways = CustomGateway.own_gateways
@active_gateway = PaymentConfiguration.config_va... |
class Admin::SolutionTagsController < ApplicationController
layout 'admin'
# 需要管理员权限
before_action :require_is_admin
# 全部标签
def index
@solution_tags = SolutionTag.all
end
# 新建方案标签
def new
@solution_tag = SolutionTag.new
end
# 建立方案标签
def create
@solution_tag = SolutionTag.new(sol... |
$:.push File.expand_path('../lib', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'administrate-field-trix'
gem.version = '0.0.3'
gem.authors = ['Ian Walter', 'Noah Settersten']
gem.email = ['public@iankwalter.com']
gem.homepage = 'https://github.com/appjumpstart/administrate-field-trix'
gem.summary ... |
class Triangle
def initialize(input)
@num_of_rows = input
@rows = []
end
def rows
old_row = [1]
(1..@num_of_rows).each do |x|
new_row = (0..old_row.size).to_a
(0..old_row.size).each do |i|
if i == 0
new_row[0] = 1
elsif i == old_row.size
new_row[... |
class CreateFindingTechnologies < ActiveRecord::Migration[5.0]
def change
create_table :finding_technologies do |t|
t.references :finding, foreign_key: true
t.references :technology, foreign_key: true
end
end
end
|
class Manufacturers < Termcap2
self.table_name = "Manufacturers"
self.primary_key = "Id"
has_many :Terminals, class_name: :Terminal, foreign_key: :ManufacturerId
@manufacturers = self.all
@terms = []
if @manufacturers.any?
@manufacturers.each do |m|
if m.Terminals.count > 0
@terms.push m
end
end
... |
class Signpage
include PageObject
page_url("#{BASE_URL}/")
# Input Boxes
text_field(:emailfield, :css => 'input[type="Email"]')
text_field(:passwordfield, :css => 'input[type="password"]')
# Button
button(:signin_link, :css => 'a.js-signin.a.btn')
button(:signin, :css => '.btn[type="submit"]')
button(... |
require 'plugman'
#require 'pry-exception_explorer'
require 'logging'
Dir[File.join(File.dirname(__FILE__), 'vigil/**/*.rb')].each do |file|
dir = File.dirname(file)[File.dirname(__FILE__).length+1..-1]
file = File.join(dir, File.basename(file, File.extname(file)))
next if file =~ /plugin/
require_relative fi... |
class DecisionsController < ApplicationController
before_action :set_decision, only: [:show, :edit, :update, :destroy]
# GET /decisions
# GET /decisions.json
def index
@decisions = Decision.all
end
# GET /decisions/1
# GET /decisions/1.json
def show
end
# GET /decisions/new
d... |
# frozen_string_literal: true
module Crawler
class Beike < Crawler::Base
@name = 'BK_spider'
@engine = :mechanize # available engines: :mechanize, :poltergeist_phantomjs, :selenium_firefox, :selenium_chrome
@start_urls = [
'https://bj.zu.ke.com/zufang/dongcheng/rco11rt200600000001',
'https://... |
class Ticket < ActiveRecord::Base
belongs_to :user
belongs_to :location
belongs_to :violation
validates :user_id, presence: true
validates :location_id, presence: true
validates :incident_time, presence: true
end |
# -*- mode: ruby -*-
# vi: set ft=ruby :
unless Vagrant.has_plugin?("vagrant-hostmanager")
puts "This Vagrant environment requires the 'vagrant-hostmanager' plugin."
puts "Please run `vagrant plugin install vagrant-hostmanager` and then run this command again."
exit 1
end
PRODUCTS = {
:apache => {
... |
require 'rails_helper'
RSpec.describe SupplyTeachers::SupplierMarkUp, type: :model do
let(:supplier_mark_up) { described_class.new(daily_rate: daily_rate, markup_rate: markup_rate) }
let(:daily_rate) { '220' }
let(:markup_rate) { 0.44 }
describe '#worker_cost' do
it 'calculates the worker cost out of the ... |
class FanzoTip < ActiveRecord::Base
attr_accessible :content, :name
validates :content, :name, presence:true
end
|
require 'spec_helper'
describe AnswersController do
login_admin
let(:skill) { create :skill }
let(:question) { create :question, skill: skill }
let!(:first_answer) { create :answer, question: question }
let(:answer) { create :answer, question: question }
describe "POST #create" do
context "with valid... |
class DonorsController < ApplicationController
def index
if params[:search]
@donors = Donor.search(params[:search])
else
@donors = Donor.all.reverse
end
end
def show
@donor = Donor.find(params[:id])
@bloodtype = Bloodtype.where(id: @donor.bloodtype_id).first
@donation = Donation.new
... |
class Users::LoanablesController < ApplicationController
before_action :authenticate_user
before_action :set_loanable, only: [:show, :edit, :update, :destroy]
# GET /loanables
# GET /loanables.json
def index
@loanables = current_user.loanables.includes(:loan_contracts).all
end
# GET /loanables/1
#... |
module Skore
module API
class User < Chainable
include Skore::DB::User
def query
{
only: %i(id name email)
}
end
def path
'/users'
end
end
end
end
|
require 'sinatra'
require './lib/post'
require 'date'
require 'time'
class MyBlog < Sinatra::Base
before do
#You can put assignments here to apply to all route handlers
end
# route handles is where you'd need to do your logic and variable assignments
# simple logic, no object orientation, no intense logic
... |
Gem::Specification.new do |s|
s.name = 'master_data'
s.version = '0.0.4'
s.date = '2012-05-18'
s.summary = ""
s.description = ""
s.authors = ["Really English"]
s.files = ["lib/master_data.rb", "lib/master_data/master_data_parent.rb", "lib/master_data/master_data.rb", "lib/m... |
class ChatRoomsController < ApplicationController
def index
@chat_rooms = ChatRoom.all
end
def create
chat_room = ChatRoom.new(name: params[:room_name])
chat_room.save
redirect_to chat_rooms_path
end
def destroy
chat_room_must_die = ChatRoom.find(params[:id])
chat_room_must_die.dest... |
class Material < ActiveRecord::Base
has_carbon_data_stored_in_amee :profile => :project
cattr_reader :per_page
COLOUR = "#9A5AAB"
TYPE = {
:timber => AmeeCategory.new("Timber", :weight_mass, "/embodied/ice", :material => "timber", :type => "general"),
:carpet => AmeeCategory.new("Carpet", :weight_ma... |
module RSpec
module Mocks
module Methods
def stub_return_of(message)
ReturnStub.new(self, message)
end
end
end
end
class ReturnStub
def initialize(receiver, message)
@receiver = receiver
@message_sym = message.to_sym
meth = @receiver.method(@message_sym)
if @receive... |
class RenameKcOrCbColumnToRoadbikes < ActiveRecord::Migration[5.0]
def change
rename_column :roadbikes, :kc_or_cb, :tire_type
end
end
|
# frozen_string_literal: true
require 'socket'
require 'openssl'
# class for tls rpc socket
class RPCSocket
attr_reader :rpc
def initialize(hsh)
host = hsh.fetch('ip4')
port = hsh.fetch('ssl_port')
tcp_socket = TCPSocket.new(host, port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(verif... |
require "test_helper"
class UtilitiesTest < VitaeTestCase
test "we can capture stdout and stderr" do
captured_string = get_stdout_and_stderr do
puts "hello!"
print "h"
puts "i"
$stderr.print "bye!"
end
expected_string = "hello!\nhi\nbye!"
assert_equal(expected_string, ... |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_action :require_login
layout :layout
def isset_account
#redirect_to root_path if user_signed_in?
... |
class User < ActiveRecord::Base
include Clearance::User
mount_uploader :avatar, AvatarUploader
PERMITTED_ATTRS = [:email, :password, :name, :password_confirmation]
validates :name, uniqueness: true
validates :name, :presence => { :message => "can't be blank"}
validates :name, format: {
with: /\A[A-Za... |
json.cache! ['v1', @links], expires_in: 1.hour do
json.array!(@links) do |link|
json.short_url link.short_url
json.long_url link.long_url
json.clicks link.clicks
if link.user
json.extract! link.user, :email
end
end
end
|
class AddDefaultValueForOpen < ActiveRecord::Migration
def change
change_column :events, :opened, :boolean, default: true
end
end
|
# encoding: UTF-8
require 'my-gem'
require 'spec_helper'
describe Exam do
before :each do
@q1 = Test.new("Hola?", ["Si", "No", "Quizas", "Puede"], 3, 1)
@q2 = Test.new('¿Cual es la salida del siguiente codigo Ruby?' "\n" 'class Xyz' "\n"' def pots'" \n"' @nice'" \n"' end'" \n"' end '"\n\n"' xyz = Xyz.new'"... |
namespace :fail2ban do
include Shell
desc "Installs the fail2ban configs"
task :setup do
on roles(:web) do
template "fail2ban-nginx-request-limit-jail.conf.erb", "/tmp/fail2ban_jail"
sudo "mv /tmp/fail2ban_jail /etc/fail2ban/jail.conf"
template "fail2ban-nginx-request-limit-jail.conf.erb", ... |
# == Schema Information
#
# Table name: articles
#
# id :integer not null, primary key
# title :string(255)
# author_id :integer
# status :string(255)
# publish_date :datetime
# created_at :datetime
# updated_at :datetime
# department_id :integer
# issue_id :i... |
class Temperature
# TODO: your code goes here!
def initialize(option={})
if option.include?(:f)
@cdegree=((option[:f])- 32)*5.0/9.0
end
if option.include?(:c)
@cdegree=option[:c]
end
end
def in_fahrenheit
f=((@cdegree*9.0)/5.0)+32
end
def in_celsius
@cdegree
end
def self.fr... |
module Campaigns
module Show
module Charts
module Daily
class FundingDeltasPresenter < BasePresenter
def daily_funding_deltas_data
@data
end
private
def build_data
pledges_amounts_with_first_data_point = daily_reports_presenter.pledge... |
class BidsController < ApplicationController
before_action :logged_in_user
def new
@bid = Bid.new
end
def create
@bid = Bid.new(bid_params)
student = User.find_by(id: params[:user_id])
if @bid.save
redirect_to users_path
student.update_attribute(:status, "assigned")
else
... |
Politwoops::Application.routes.draw do
root :to => "tweets#index"
match "index(.:format)" => "tweets#index", :as => :index
match "tweet/:id" => "tweets#show", :as => :tweet
match "tweet/:tweet_id/thumb/:basename.:format" => "tweets#thumbnail"
match "user/:user_name" => "politicians#show", :as => :politici... |
class RenameAlertSentColumninPriorities < ActiveRecord::Migration[6.0]
def change
rename_column :priorities, :alert_sent, :priority_accomplished
end
end
|
class Tracetag < ActiveRecord::Base
set_table_name 'gpx_file_tags'
validates_format_of :tag, :with => /^[^\/;.,?]*$/
validates_length_of :tag, :within => 1..255
belongs_to :trace, :foreign_key => 'gpx_id'
end
|
class Series
def initialize(string)
@numbers = string.split('').map(&:to_i)
end
def slices(slice_size)
assert_valid_slice_size(slice_size)
@numbers.each_cons(slice_size).to_a
end
private
def assert_valid_slice_size(slice_size)
fail ArgumentError if slice_size > @numbers.size
end
end
|
require 'rails_helper'
RSpec.describe Video, type: :model do
describe '#base_dir' do
let(:video) { build_stubbed(:video) }
it 'returns base dir for video storage' do
expect(video.base_dir).to eq("videos/#{video.id}")
end
end
describe '#path' do
let(:video) { build_stubbed(:video) }
b... |
class SessionsController < Devise::SessionsController
after_filter :after_login, :only => :create
def after_login
change_challenges_to_dormant
change_challenges_to_expired
challenges_needed = (3 - num_active_challenges)
if challenges_needed > 0
create_challenges(challenges_need... |
require 'formula'
class TokyoCabinet <Formula
@url='http://1978th.net/tokyocabinet/tokyocabinet-1.4.33.tar.gz'
@homepage='http://1978th.net/tokyocabinet'
@sha1='c3ded8ee0bde93f072b9436a6244dc7690abd5c6'
def install
system "./configure", "--prefix=#{prefix}", "--enable-fastest"
system "make"
system... |
module Fog
module Compute
class Aliyun
class Real
# {Aliyun API Reference}[https://docs.aliyun.com/?spm=5176.100054.3.1.DGkmH7#/pub/ecs/open-api/disk&detachdisk]
def detach_disk(instanceId, diskId,options={})
action = 'DetachDisk'
sigNonce = randonStr()
time ... |
namespace :db do
desc 'Erase and Fill database'
task populate: :environment do
[CategoryRecommendation,
Recommendation,
Activity,
Professor,
ProfessorCategory,
ProfessorTitle,
DisciplineMonitor,
Academic,
Discipline,
Period,
Matrix, Faq,
StaticPage].each(... |
class Message
def welcome
puts "WELCOME TO THE MASTERMIND GAME!"
puts "Would you like to (p)lay, read the (i)nstructions, or (q)uit?"
end
def initialize
choice
end
def choice
arr_choice = ['p', 'i', 'q']
if
choice == "p" || choice == "play"
User.user_c... |
class LinkedLists
def initialize(data = nil)
@head = Node.new
@head.value = data
end
def append(data)
if @head.value == nil
@head.value = data
else
current_node = @head
while current_node.next_node != nil
current_node = current_node.next_node
end
current_node... |
class Dota::Snapshot
include Mongoid::Document
include Mongoid::Timestamps::Created
include ActiveModel::Validations
include ActiveModel::Serialization
embeds_many :heroes, class_name: 'Dota::Hero', cascade_callbacks: true
def self.most_recent
asc(:created_at).last
end
end
|
describe package('docker-ce') do
it { should be_installed }
end
describe package('docker-ce-cli') do
it { should be_installed }
end
describe package('containerd.io') do
it { should be_installed }
end
describe service('docker') do
it { should be_enabled }
it { should be_running }
end |
describe "Rool::Not" do
describe '#process' do
## Exceptions
it 'raises an exception if more than one child rule is passed to the constructor' do
expect{(Rool::Not.new(Rool::False.new, Rool::True.new).process)}.to raise_error("Rool::Not can only accept one rule object")
end
## Expect True
... |
class RedCardsController < ApplicationController
before_action :set_red_card, only: [:show, :edit, :update, :destroy]
# GET /red_cards
# GET /red_cards.json
def index
@red_cards = RedCard.all
end
# GET /red_cards/1
# GET /red_cards/1.json
def show
end
# GET /red_cards/new
def new
@red_c... |
class BookItem < ApplicationRecord
belongs_to :book
belongs_to :shelf
end
|
module Tooth
module PageObject
def within scope_locator, &block
within_scope_klass = Class.new
within_scope_klass.extend PageObject
within_scope_klass.instance_variable_set :@page_element, page_element
within_scope_klass.element_with_finders = -> { element_with_finders.find(scope_locator) ... |
require 'set'
# set = (0...3*n).to_a
#
#
# def lexicographically_before(xs, ys)
# xs.empty? && ys.empty?
#
# xs.zip(ys).all? { |x, y| y.nil? ? false : x.nil? || x <= y }
# end
#
# x3s.flat_map do |a|
# x3s.flat_map do |b|
# x3s.map do |c|
# [a, b, c]
# statistics = [
# a.length,
# ... |
require_relative('../db/sql_runner.rb')
class Ticket
attr_accessor :customer_id, :film_id, :screening_id
attr_reader :id
def initialize(ticket)
@id = ticket['id'].to_i if ticket['id']
@customer_id = ticket['customer_id'].to_i
@film_id = ticket['film_id'].to_i
@screening_id = ticket['screening_i... |
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rawk_log/version'
Gem::Specification.new do |spec|
spec.name = "rawk_log"
spec.version = RawkLog::VERSION
spec.authors = ["Chris Hobbs", "Ian Heggie"]
spec.email ... |
# frozen_string_literal: true
require "test_helper"
require "generators/boring/paper_trail/install/install_generator"
class PaperTrailInstallGeneratorTest < Rails::Generators::TestCase
tests Boring::PaperTrail::InstallGenerator
setup :build_app
teardown :teardown_app
include GeneratorHelper
include ActiveS... |
require "spec_helper"
describe ".validates_email_format_of" do
before do
User.validates_email_format_of :email, :corporate_email, :allow_blank => false
Buyer.validates_email_format_of :email, :message => "is not a valid e-mail"
Person.validates :email, :email => true
end
VALID_EMAILS.each do |email|... |
class AddCourseToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :course, index: true, foreign_key: true
end
end
|
OUTPUT_PATH = ARGV.first + "/"
def file_name(klass)
file_name = OUTPUT_PATH + klass.to_s.downcase
file_name.gsub!("::", "/")
file_name << ".rb"
return file_name
end
def dir_names(file_name)
last_slash = file_name.rindex("/")
return nil if last_slash.nil?
file_name[0...last_slash]
end
d... |
def variants(string)
base = string.split("/").map(&:chars)
[
base,
base.map(&:reverse),
base.reverse,
base.reverse.map(&:reverse),
base.transpose,
base.transpose.map(&:reverse),
base.transpose.reverse,
base.transpose.reverse.map(&:reverse)
].uniq.map do |variant|
variant.map(&... |
FixtureBuilder.configure do |fbuilder|
# rebuild fixtures automatically when these files change:
fbuilder.files_to_check += Dir["spec/factories/*.rb"]
end
|
module CalendarTable
class Base
def initialize(year:nil, month: nil)
@year = year || Date.today.year
@month = month || Date.today.month
end
def table
last_day = Date.new(@year, @month, -1).day
table = []
# Set content
1.upto(last_day) do |day|
table.push htmli... |
class Response < ActiveRecord::Base
belongs_to :company
belongs_to :individual_attribute
has_many :response_employee_types
has_many :employee_types, :through => :response_employee_types
end
|
module Favable
extend ActiveSupport::Concern
included do
has_many :favorites, as: :favable, dependent: :destroy
end
def favorited_by? user
favorites.find_by(user_id: user.id).present?
end
def favorited_by user
favorites.create user: user
end
def unfavorited_by user
favorites.find_by(... |
#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
SweetArticlesRails::Application.load_tasks
namespace :db do
desc "Migrate Leg... |
RSpec.describe "ProtectMyID.com Production UI" do
it "takes screenshots for registration process", :smoke => true, :regression => true do |example|
@app.home.firstName.set "First Name"
@app.home.lastName.set "Last Name"
@app.home.zipCode.set "92626"
screenshot_and_save_page
@app.home.submit.... |
class CreateStoreItems < ActiveRecord::Migration[5.0]
def change
create_table :store_items do |t|
t.string :name
t.string :description
t.decimal :price, precision: 5, scale: 2
t.integer :stock
t.text :options
t.attachment :image
t.timestamps
end
end
end
|
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
#
# P A H N
# A P L S I I G
# Y I R
#
# And then read line by line: "PAHNAPLSIIGYIR"
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string text, int n... |
require 'spec_helper'
describe TextureGenerator do
let(:texture_generator) { TextureGenerator.new(card) }
let(:card) do
double(Card, image_path: 'spec/samples/texture_generator/card_pic.png', attribute: 'TRAP')
end
let(:sample_file) { 'spec/samples/texture_generator/sample_generate.bmp' }
describe '#gen... |
Rails.application.routes.draw do
get '/flights' => 'flights#index'
root 'flights#index'
resources :bookings, only: [:new, :create, :show]
end
|
module SweepingHelper
# sweep (delete) the contents of a directory in the public cache
def self.sweep_path(path)
cache_dir = ActionController::Base.page_cache_directory
unless cache_dir == RAILS_ROOT+"/public"
FileUtils.rm_r(Dir.glob(cache_dir+"/#{path}/*")) rescue Errno::ENOENT
RAILS_DEFAULT_L... |
$LOAD_PATH.unshift File.expand_path('../lib', __FILE__)
begin
require 'bundler'
Bundler::GemHelper.install_tasks
rescue LoadError => e
$stderr.puts e
end
desc "run specs"
task(:spec) { ruby '-S rspec spec' }
task :default => :spec
task :test => :spec
|
class AddPropertiesToItem < ActiveRecord::Migration
def change
add_column :items, :properties, :jsonb, default: {}
end
end
|
module Agents
class FremeNifConverterAgent < Agent
include FormConfigurable
include WebRequestConcern
include NifApiAgentConcern
default_schedule 'never'
description <<-MD
The `FremeNifConcerterAgent` allows to convert plain text, a document in any format supported by [e-Internalisation](h... |
# frozen_string_literal: true
module Checkups
class NotificationTimer
def initialize(frequency, status)
@frequency = frequency
@status = status
end
def now?
case @status
when :warning, :error
true
else
case @frequency
when :always
true
... |
#!/usr/bin/env ruby
# ==================Importing required modules==============
require 'csv'
require_relative 'distributor_helper'
# ==================Including DistributorHelper module ==============
include DistributorHelper
class Distributor
# ==================declaring class variables ==============
@@region_... |
# frozen_string_literal: true
RSpec.describe SeeYouCup::Parser do
it 'raises no error for existing file' do
expect { SeeYouCup::Parser.new("#{__dir__}/samples/lotnik.cup") }.not_to raise_error
end
it 'raises FileNotFound error for missing file' do
expect { SeeYouCup::Parser.new('/no/such/file') }.to rai... |
require 'thor'
module Xcadaptor
class Config < Thor
require_relative './project'
desc 'ssl [options]' , "config ssl according [options]"
option :black ,:type => :array , :banner => "ssl black domain" , :aliases => :b
option :white ,:type => :array , :banner => "ssl white domain" , :aliases ... |
require 'packman'
require 'packman/funpackfile'
require 'packman/proc_runner'
require 'launchy'
module Packman
SETTINGS_ROOT = File.expand_path("../../settings", __FILE__)
end
class Packman::WebSettings
def self.generate(filename)
runner = new(Packman::Funpackfile.new(filename))
runner.start!
end
def... |
class AddImagesFolderNameRemoveThumbAndIndexImgName < ActiveRecord::Migration
def self.up
change_table :projects do |t|
t.rename :thumb_img_filename, :imgs_folder_name
t.remove :index_img_filename
end
end
def self.down
change_table :projects do |t|
t.rename :imgs_folder_name, :thumb_img_filena... |
control 'azure_remote_state' do
title 'Check if the Example Resource Group matches expectations'
comment 'see https://docs.microsoft.com/en-us/rest/api/ for valid queries'
impact 1.0
describe azure_resource_group(name: 'Inspec-Azure') do
# Check if the Resource Group has tags
it { shoul... |
require_relative "n";
class M;
def self.eg;
Array.new(9) { Array.new(9) { N.new(0) } }
end
def initialize(g = self.eg)
@g = g
end
def h
v.transpose
end
def onelasttry;
puts "I'm just 'bout done with this"
end
def prn
puts " #{(0.... |
class Special < ApplicationRecord
validates_presence_of :name
validates :run_time, presence: true, numericality: {
only_integer: true, :greater_than_or_equal_to => 0
}
validates_presence_of :thumbnail
belongs_to :comedian
def self.average_length
Special.average(:run_time).round(2)
end
end
|
class WelcomeController < ApplicationController
def index
@messages = Message.limit(5).order(id: :desc).all
@last_id = @messages.last.nil? ? 0 : @messages.last.id
end
end
|
#! /usr/bin/env ruby
require 'git'
def git
Git.open( '/tmp/chef-repo/.chef' )
end
def get_branches
branches = git.branches.local.map do | branch |
branch.name
end
branches.reject do | branch |
branch == 'master'
end
end
def backup
src = File.expand_path( '~' )
dest = '/tmp/chef-repo'
fail... |
class MovieSearchFacade
def initialize
@movie_service = MovieDBService.new
end
def get_movies(keyword)
if keyword.nil?
top_40
else
keyword_search(keyword)
end
end
def top_40
movies_results = @movie_service.top_rated_movies
@movies = movies_results.map do |movie_info|
... |
require 'rails_helper'
RSpec.describe CreateUserDefaultsJob, :type => :job do
let(:user) { FactoryBot.create(:user) }
it 'should create standard project statuses' do
CreateUserDefaultsJob.new().perform(user)
ActsAsTenant.with_tenant(user) do
expect(ProjectStatus.count).to eql(4)
end
end
it... |
# frozen_string_literal: true
RSpec.describe LightSerializer::VERSION do
it { is_expected.to be_present }
end
|
class Book < ApplicationRecord
belongs_to :user
validates :title, :author, :description, :url, :user_id, presence: true
scope :username, -> { User.find_by(:id => Book.user_id) }
end
|
class Api::TasksController < ApplicationController
def index
selectedSortType = params[:selectedSortType] || "deadline"
hasJoined = false
@tasks = Task.all
if selectedSortType == "partners.name" || selectedSortType == "partners.name desc"
@tasks = @tasks.joins('LEFT OUTER JOIN partners ON partn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.