text stringlengths 10 2.61M |
|---|
class Book < ApplicationRecord
validates :gender, :author, :image, :title, :editor, :year, presence: true
has_many :rents, dependent: :destroy
end
|
class AddColumnSendtimesToPayments < ActiveRecord::Migration[5.1]
def change
add_column :payments, :send_times, :integer, :default => 0
end
end
|
# Copyright (c) 2012 Ryan J. Geyer
#
# 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, modify, merge, publish,
# dis... |
class Payee < ActiveRecord::Base
belongs_to :account
has_paper_trail
validates :name, presence: true, uniqueness: { scope: :account_id }
end
|
class CustomerSet < ActiveRecord::Base
belongs_to :user
has_many :custom_queries
accepts_nested_attributes_for :custom_queries
def get_customers(user)
fields = self.custom_queries.map { |c| c.field }
@customers = user.customers.select { |c| c.has_fields(fields) }
self.custom_queries.each do |c_q... |
# frozen_string_literal: true
require 'spec_helper'
require 'json'
RSpec.describe Sinatra::ProblemDetails do
def mock_app(&block)
super do
register Sinatra::ProblemDetails
class_eval(&block)
end
end
def results_in(obj)
expect(JSON.parse(get('/').body)).to eq(obj)
end
it "encodes ob... |
require 'pp'
require 'pry'
class Grid
attr_accessor :rows, :width, :height
def initialize(width, height)
@width, @height = width, height
@rows = Array.new(height) { Array.new(width) }
end
def populate
@rows.each_with_index do |row, x|
row.each_with_index do |cell, y|
row[y] = Cell.new... |
class VirtualCardsController < ApplicationController
def create
virtual_card_resp = mutual_auth_req("/vpa/v1/accountManagement/VirtualCardRequisition", "post", request_body)
virtual_card_resp
end
def cvv
end
private
def getCorrelationId()
# Passing correlation id header (ex-correlation-id) is optional... |
# == Schema Information
#
# Table name: cities
#
# id :integer not null, primary key
# country_id :integer not null
# region_id :integer not null
# name :string(45) not null
# latitude :float not null
# longitude :float not null
# timezone ... |
class ApplicationController < ActionController::Base
helper_method :logged_in?
helper_method :current_user
#for redirects
def current_user
if session[:user_id]
@current_user ||= User.find_by(id: session[:user_id])
end
end
#for controllers
def require_login
redirect_to login_path un... |
class Backlink < ActiveRecord::Base
include Checkable
belongs_to :project
validates :referrer_page, url: { allow_blank: true }, presence: true
validates :referent_domain, presence: true
validates :project_id, presence: true
after_save :send_notification
scope :expire_in, ->(period) do
where(expire... |
class User < ActiveRecord::Base
has_many :lists
SALT = '$2a$10$D1OPM3oiaDlfkW0vU1sfbvlq.'
before_save { self.email = self.email.downcase }
before_create :create_remember_token
before_create :encrypt_password
after_save :clear_password
validates :username, presence: true,
uniqueness: true... |
class Job < ApplicationRecord
belongs_to :user
validates :title, presence: true
validates :position, presence: true
scope :recent_first, -> { order('created_at DESC') }
scope :archived, -> { where(archived: true) }
scope :active, -> { where(archived: false) }
end
|
Rails.application.routes.draw do
#welcome controller
root "welcome#index"
#sessions
get "/signin" => "sessions#new"
post "/signin" => "sessions#create"
delete "/signout" => "sessions#destroy"
#users
resources :users
#rides
resources :rides
#attractions
resources :attractions
end |
class MetricDescription
include Datapathy::Model
service_type :measurements
resource_name :AllMetricDescriptions
persists :metric_type_pattern, :description
validates_presence_of :metric_type_pattern
end
|
require './lib/car.rb'
describe Car do
it 'check method change color' do
subject.change_color("blue")
expect(subject.color).to eq "blue"
end
let (:driver) {instance_double('driver', name: 'julie') }
it 'check if class has an driver' do ... |
JSONAPI.configure do |config|
# built in paginators are :none, :offset, :paged
config.default_paginator = :paged
config.default_page_size = 10
config.maximum_page_size = 20
config.allow_sort = false
end
|
require "minitest/autorun"
require_relative"match.rb"
class Testmatch < Minitest::Test
def test_matches
b = "123"
a = "123"
assert_equal(3,number_matches(a,b))
end
def test_matching
a = "3256"
b = "2536"
assert_equal(1,number_matches(a,b))
end
def test_number1
assert_equal(1,1)
en... |
class CreateInvoices < ActiveRecord::Migration[5.0]
def change
create_table :invoices do |t|
t.references :customer, references: :company, foreign_key: true
t.references :sales_order, foreign_key: true
t.date :invoice_dt
t.string :ref_no
t.decimal :net_cost
t.decimal :net_vat
... |
ActiveAdmin.register Account do
# See permitted parameters documentation:
# https://github.com/activeadmin/activeadmin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
permit_params :account_id, :api_domain, :api_key
controller do
actions :all, :except => [:edit,:show]
end
config.batch_a... |
class AddDefaultsToEvents < ActiveRecord::Migration
def change
change_column :events, :name, :string, :default => "Event Name"
change_column :events, :description, :text, :default => "Event Description"
change_column :events, :start_on, :datetime, :default => Time.now
change_column :events, :end_on, :... |
module UserConcerns
module Achievements
extend ActiveSupport::Concern
# SCORE_BY_INSTITUTION_QUERY = <<-SQL
# SELECT sum(COALESCE(p.score, a.default_score))
# FROM user_achievements ua
# INNER JOIN achievements a
# ON ua.achievement_id = a.id
# LEFT JOIN points p
# ON p... |
require 'test_helper'
class Admin::AboutusControllerTest < ActionController::TestCase
setup do
@admin_aboutu = admin_aboutus(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:admin_aboutus)
end
test "should get new" do
get :new
assert_r... |
class AddColumnToUsersPhone < ActiveRecord::Migration
def change
add_column :users, :phone, :string
add_column :users, :locked, :boolean
add_column :users, :email_frequency, :string
end
end
|
class RenameColumnUserIdTubeOperations < ActiveRecord::Migration
def self.up
rename_column :tube_operations, :user_id, :performer_id
end
def self.down
rename_column :tube_operations, :performer_id, :user_id
end
end
|
#!/usr/bin/env ruby
# frozen_string_literal: true
lib = File.expand_path('../lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'thor'
require 'logger'
require 'quicken'
require 'quicken/cli/init'
require 'quicken/commands/autoloader'
LOGGER = Logger.new(STDOUT)
LOGGER.level = Logger::WA... |
class MembershipsRenameMemberType < ActiveRecord::Migration
def self.up
rename_column :memberships, :member_type, :member_role
end
def self.down
rename_column :memberships, :member_role, :member_type
end
end
|
class CleanupFights < ActiveRecord::Migration
def change
remove_column :fights, '{:index=>true}_id'
add_reference :logs, :fights, index: true
end
end
|
# http://projecteuler.net/index.php?section=problems&id=55
#
# If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
#
# Not all numbers produce palindromes so quickly. For example,
#
# 349 + 943 = 1292,
# 1292 + 2921 = 4213
# 4213 + 3124 = 7337
#
# That is, 349 took three iterations to arrive at a p... |
class CreateAgendas < ActiveRecord::Migration
def change
create_table :agendas do |t|
t.string :name
t.string :start
t.string :finish
t.string :parent_id
t.string :category
t.timestamps
end
end
end
|
require_relative "board"
class King < Piece
attr_accessor :color, :pos, :board
def initialize(color, pos, board)
@color = color
@pos = pos
@board = board
end
def slide_set
start = @pos
cur_x, cur_y = start
moves = [[1,1], [1,-1], [-1,1], [-1,-1]]
pos_slides = []
moves.each do ... |
class Artist < ApplicationRecord
has_many :medias, dependent: :destroy
validates :name, :description, :photo, presence: true
mount_uploader :photo, PhotoUploader
end
|
class Like < ApplicationRecord
belongs_to :liked_user, class_name: 'User', foreign_key: 'liked_user_id'
belongs_to :liked_by_user, class_name: 'User', foreign_key: 'liked_by_user_id'
validates :liked_user_id, :liked_by_user_id, presence: true
end
|
module Entity
class VoidTileType
def self.id
-1
end
def self.name
'Void'
end
def self.colour
'black'
end
def self.description
''
end
def self.search_rate
0
end
def self.hide_rate
0
end
def self.search_table
[]
end
def self.statuses
[]
end
def traversib... |
require 'levenshtein'
# LINEのIDを取得できます
def get_id(event)
case event["type"]
when "user"
return event["userId"]
when "group"
return event["groupId"]
when "room"
return event["roomId"]
else
return "error"
end
end
# 編集距離を求めてくれます
def levenshteinWord(title, lectures)
# title = "薬"
# lecture... |
require 'will_paginate/array'
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter ... |
module CreatedByHelper
def text_created_by(model, action = "create", mode = "short")
begin
if action.include?("update")
id = model.updated_by
time = model.updated_at
else
id = model.created_by
time = model.created_at
end
user = <%= user.camelize %>.<%= optio... |
class ModifyLoanColumnNames < ActiveRecord::Migration
def change
rename_column :loans, :requestDate, :request_date
rename_column :loans, :amountRequested, :amount_requested
rename_column :loans, :fundingDeadline, :funding_deadline
rename_column :loans, :fundedDate, :funded_date
rename_column :loan... |
module Fact
class ClearTool
def invoke(command_str)
return `cleartool #{command_str}`
end
end
class ClearCase
def initialize
@cleartool = ClearTool.new
end
# Get the name of the current stream.
#
def get_current_stream
return @cleartool.invoke("lsstream -s").rstrip
end
# Get t... |
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
admin = User.create!(name: "Example User",
email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar")
admin.toggle!(:... |
Rails.application.routes.draw do
devise_for :users
resources :clocks, except: [:destroy]
root to: 'clocks#new'
end
|
class Dashboard::RequestOffsController < ApplicationController
load_and_authorize_resource class: RequestOff.name
load_and_authorize_resource :user
include ApplicationHelper
def index
@request_offs = @request_offs.page(params[:page])
.per Settings.per_page.dashboard.request_off
end
def show
en... |
class Record < ActiveRecord::Base
has_many :record_field_options,:dependent=>:destroy
has_many :student_records,:foreign_key=>'additional_field_id',:dependent=>:destroy
has_many :record_addl_attachments,:through=>:student_records
belongs_to :record_group
validate :options_check
before_validation :strip_whit... |
shared_examples 'ProfileCreator::Auth' do
subject { described_class.new(user, auth) }
let(:user) { create(:user) }
describe '#perform' do
let(:auth) { { info: { nickname: 'nickname' } } }
specify 'without profile with such nickname' do
subject.perform
expect(user.profile.nickname).to eq 'nic... |
#encoding: utf-8
module Admin::SearchHelper
class FormBuilder < ActionView::Helpers::FormBuilder
delegate :content_tag, to: :@template
%w[text_field text_area password_field].each do |method_name|
define_method(method_name) do |name, *args|
options = args.extract_options!
args << ({cl... |
module Effect
class Reloadable
attr_reader :ammo_type
attr_reader :capacity
def initialize(parent, ammo_type, capacity)
@parent = parent
@ammo_type = ammo_type.to_sym
@capacity = capacity.to_i
end
def name
'Reload'
end
def activate_self_intent(intent)
intent.name = name
intent.outco... |
#!/home/kenb/.rvm/rubies/ruby-2.1.3/bin/ruby -w
# Daemon 'one_shot', used to create an external http post "Wake up and water the flowers" event at the specified Time
# Input parameters:
# wake_up_time
# an integer, with a resolution of seconds since the Unix Epoch.
# uri
# a CGI-encoded string value cont... |
class ChangeCategoryTypeIdOnEventTypes < ActiveRecord::Migration[5.0]
def up
change_column :event_types, :event_category_id, :string
rename_column :event_types, :event_category_id, :event_category
end
def down
rename_column :event_types, :event_category, :event_category_id
change_column :event_ty... |
module Hermes
module Plugin
##
# Plugin for searching Wikipedia.
#
class Wikipedia
include Cinch::Plugin
match(/w\s+(.+)/, :method => :execute)
match(/wiki\s+(.+)/, :method => :execute)
##
# The URL of Wikipedia's search system.
#
# @return [String]
... |
require_relative './helper.rb'
describe 'TagHelpers' do
context 'for #tag method' do
it 'should support tags with no content no attributes' do
app.tag(:br).should have_selector(:br)
end
it 'should support tags with no content with attributes' do
actual_html = app.tag(:br, :style => 'clear:bo... |
class Investment < ActiveRecord::Base
validates :user_id, presence: true, numericality: true
validates :company_id, presence: true, numericality: true
belongs_to :user
belongs_to :company
end
|
class FontLifeSavers < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/lifesavers"
desc "Life Savers"
homepage "https://fonts.google.com/specimen/Life+Savers"
def install
(share/"fonts").install "LifeSavers-Bold.ttf"
(share/"fonts"... |
class Api::UsersController < ApplicationController
before_filter :require_signed_in!
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:password, :username)
end
end
|
class StudentsController < ApplicationController
def new
@student = Student.new
end
def create
@student = Student.new(student_params)
if @student.save
session[:student_id] = @student.id
redirect_to @student
else
@errors = @student.errors.full_messages
render "new"
end
... |
class AddFinancingDoneToForecasts < ActiveRecord::Migration
def change
add_column :forecasts, :financing_done, :boolean, default: false
end
end
|
#
# CampfireHandler -- a simple Campfire handler for Chef
#
# Copyright 2011, Estately, Inc.
#
# 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... |
class Guest
include Role::Guest
def initialize
make_initial_admin if initial_admin?
end
def initial_admin?
@initial_admin ||= User.count == 0
end
def to_user
nil
end
private
def make_initial_admin
extend Role::InitialAdmin
end
end
|
require 'spec_helper'
require 'webmock/rspec'
describe Gibbon::APIRequest do
let(:api_key) { "1234-us1" }
before do
@gibbon = Gibbon::Request.new(api_key: api_key)
@api_root = "https://us1.api.mailchimp.com/3.0"
@basic_auth_credentials = ['apikey', api_key]
end
shared_examples_for 'client error h... |
class Curl < Package
desc 'Get a file from an HTTP, HTTPS or FTP server'
homepage 'http://curl.haxx.se/'
url 'https://curl.haxx.se/download/curl-${version}.tar.bz2'
release version: '7.58.0', crystax_version: 4
depends_on 'openssl'
depends_on 'libssh2'
build_options copy_installed_dirs: ['bin', 'inclu... |
#encoding: utf-8
class TasksPdf < Prawn::Document
include ActionView::Helpers::TextHelper
def initialize(project)
super(top_margin: 20, page_layout: :landscape)
@project = project
today_date
project_name
pagination
project_features
end
def project_name
text "#{@project.name.tit... |
class BoardPermission < ActiveRecord::Base
belongs_to :board
serialize :permission
end
|
class Collectible < ApplicationRecord
belongs_to :user
has_many :nfts, dependent: :destroy
has_many :plots, dependent: :destroy
has_many_attached :photos
has_many :asks, dependent: :destroy
has_many :bids, dependent: :destroy
include PgSearch::Model
pg_search_scope :search_by_brand_and_model,
aga... |
require File.dirname(__FILE__) + '/test_helper.rb'
context "discovery" do
specify "should discover the Util workling, since it subclasses Workling::Base and is on the configured Workling load path." do
discovered = Workling::Discovery.discovered
discovered.map(&:to_s).should.include "Util"
end
specify... |
class Profile < ActiveRecord::Base
self.abstract_class = true
has_one :user, as: :profile, dependent: :destroy
belongs_to :language
scope :shoppers, lambda { where(role: "shopper") }
before_validation :set_language
def guest?
role?("guest")
end
def admin?
role?("admin")
end
def sales... |
# frozen_string_literal: true
module AutomaticUpdate
# https://www.usps.org/cgi-bin-nat/grades/bocmods.cgi
class BOCDataRequest < DataRequest
REQUEST_URL = 'https://www.usps.org/cgi-bin-nat/grades/doquery.cgi?%7C%7C%7Ctools'
DOWNLOAD_URL = 'https://www.usps.org/info/temp/0525_bocmods.csv'
REQUEST_HEADE... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe DifferentiateController, type: :controller do
context 'GET /differentiate/*' do
let(:answer) { '6x + 1' }
let(:polynomio) { '/3/1/1' }
before { get "differentiate", params: { polynomio: polynomio } }
it 'returns HTTP statsu 200' ... |
# WARNING, YOU SHOULD NOT BE EDITING THIS FILE
class SpecialMoveOld < Move
def initialize title, options = {}
@title = title
options[:hit_chance] = 75
options[:hit_damage] ||= nil
options[:stun_chance] ||= 0
options[:heal_amount] ||= nil
points = 100 -
(options[:hit_damage] || 0) - ... |
class Recipe < ApplicationRecord
belongs_to :user
has_many :recipe_amounts, dependent: :destroy
has_many :items, through: :recipe_amounts
accepts_nested_attributes_for :recipe_amounts, allow_destroy: true, update_only: true, reject_if: :all_blank
validates :recipe_name, presence: true, length: { minimum: 5 }
... |
class Signup < ActiveRecord::Base
validates :email, :presence => true,
:uniqueness => true,## This should be done at the DB this is too expensive in rails
:format => { :with => CustomValidators::Emails.email_validator },
:length =>... |
require 'test_helper'
class Refine::ReconcileTest < APITest
setup do
# delete_indices
end
def query_for(type, term)
"{\"q0\":{\"query\":\"#{term}\",\"type\":\"#{type}\",\"type_strict\":\"should\"}}"
end
test 'GET /refine/reconcile requires a callback param' do
get '/refine/reconcile'
assert... |
# -*- encoding: utf-8 -*-
require "flickraw"
FlickRaw.api_key = ENV['FLICKR_API_KEY']
FlickRaw.shared_secret = ENV['FLICKR_API_SECRET']
open("flickraw-cached.rb", "w") {|f|
f.puts %{require 'flickraw'}
f.puts %{FlickRaw::VERSION << '.#{Time.now.strftime("%Y%m%d")}-cached'}
f.puts 'ms = %w{' + flickr.reflectio... |
module DynamoDBSpecHelpers
def create_table(table_name, opts)
dynamodb_client.create_table(
{
table_name: table_name,
provisioned_throughput: { read_capacity_units: 1, write_capacity_units: 1 }
}.merge(opts)
)
wait_till_table_create(table_name)
end
def drop_table(table_nam... |
class Weapon
attr_accessor :effects, :perks, :name
def initialize(template)
@name = template.name
@perks = template.apply_perks
@effects = []
@effects = template.apply_effects if template.respond_to?(:apply_effects)
end
def apply_perks(attributes)
modified_att = attributes.clone
@perks... |
require 'spec_helper'
describe "touch_data/index" do
before(:each) do
assign(:touch_data, [
stub_model(TouchDatum,
:acceleration_avg => 1.5,
:duration => 1.5,
:max_radius => 1.5,
:rotation_avg => 1.5,
:x_delta => 1.5,
:y_delta => 1.5,
:group => 2,
... |
# -*- encoding : utf-8 -*-
require 'rails_helper'
RSpec.describe UsersController, type: :routing do
describe 'routing' do
it 'routes to #show' do
expect(get: '/users/1').to route_to('users#show', id: '1')
end
it 'routes to #update' do
expect(put: '/users/1').to route_to('users#update', id: '... |
# encoding: utf-8
#
# © Copyright 2013 Hewlett-Packard Development Company, L.P.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... |
require 'rails_helper'
describe 'devise/registrations/new.html.haml' do
let(:user) {mock_model("User").as_new_record}
before do
allow(user).to receive_messages(email: nil, password: nil, password_confirmation: nil)
assign(:resource, user)
render
end
it 'has new_user form' do
expect(rendered... |
class Teste < ApplicationRecord
belongs_to :suite
validates_uniqueness_of :nome, message: "Já existe um teste com o nome inserido"
scope :filter_by_nome_teste, -> (nome) { where nome: nome }
end
|
class LoanContract < ApplicationRecord
belongs_to :loanable
has_one :borrower
end
|
class PostalCode < ActiveRecord::Base
self.table_name = 'codigos_postales'
scope :with_code, -> (code) { where(codigo_postal: code) }
def self.with_code_hint(code_hint)
PostalCode.where('codigo_postal LIKE :prefix', prefix: "#{code_hint}%")
.order(codigo_postal: :asc)
.distinct
.pluck(:cod... |
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :prototype, counter_cache: true
validates :text, length: { maximum: 500 }, presence: true
end
|
default_run_options[:pty] = true
set :application, "installd"
set :deploy_to, "/var/rails/#{application}"
set :scm, :git
set :repository, "git@git.floehopper.org:#{application}"
server "argonaut.slice", :app, :web, :db, :primary => true
set :shared_children, shared_children + %w(cache)
after "deploy:update_code"... |
class UpdateForeignKeysOnPostAttachments < ActiveRecord::Migration
def change
remove_foreign_key :post_attachments, :posts
add_foreign_key :post_attachments, :posts, on_delete: :cascade
end
end
|
class Api::V1::MoviesController < Api::V1::ApiController
def index
endpoint_args do
requires :term, type: String
end
movies = Api::V1::MoviesPresenter.new(Tmdb::Movie.find(params[:term]))
respond_with movies
end
def popular
movies = Api::V1::MoviesPresenter.new(parse_results(Tmdb::Mov... |
require 'fluent/plugin/in_tcp'
require_relative 'logplex'
module Fluent
class HerokuSyslogInput < TcpInput
Plugin.register_input('heroku_syslog', self)
include Logplex
config_param :format, :string, :default => SYSLOG_REGEXP
config_param :drain_ids, :array, :default => nil
private
def on_m... |
class CreateProfileDescriptions < ActiveRecord::Migration
def change
create_table :profile_descriptions do |t|
t.string :name
t.text :description
t.string :one_liner
t.text :bullet_description
t.string :big5_dimension
t.string :holland6_dimension
t.string :code
t.t... |
module ActiverecordConsistencyOfConstraints
def load_activerecord_models
Rails.application.eager_load!
ActiveRecord::Base.subclasses.select do |activerecord_class|
activerecord_class.parent != ActiveType
end
end
def find_missing_indexes
missing_indexes = load_activerecord_models.inject([]) ... |
class FacilitiesController < ApplicationController
def show
@facility = Facility.find(params[:id])
end
end
|
class Ability
include CanCan::Ability
def initialize(user, request = nil)
can :read, User
can :read, Answer
can :manage, Poke
can :read, Campaign
can :create, Campaign
can :read, Update
can :read, Influencer
can :search, Influencer
if user && user.admin?
can :manage, :all... |
class RenameInvalidToken < ActiveRecord::Migration
def change
rename_table :invalid_tokens, :tokens
end
end
|
class WelcomeController < ApplicationController
# before_action :require_logged_in
def home
if !logged_in?
redirect_to new_user_path
else
render root
end
end
end
|
module ApplicationHelper
@@upvote_icon_classes = "vote_icon grey glyphicon glyphicon-chevron-up"
@@downvote_icon_classes = "vote_icon grey glyphicon glyphicon-chevron-down"
def upvote_icon_for(link)
classes = @@upvote_icon_classes
classes += " selected" if link.upvoted_by?(current_user)
return conte... |
# == Schema Information
#
# Table name: posts
#
# id :integer not null, primary key
# title :string not null
# content :string
# visible :boolean default(FALSE)
# user_id :integer not null
# type :string
# created_at :datetime not null
# u... |
# 单页的文档页面
# 采用 Markdown 编写
require 'redcarpet'
class Page
include ApplicationRecord
include BaseModel
include MarkdownBody
include Searchable
# acts_as_cached version: 1, expires_in: 1.week
field :slug, type: String
field :title, type: String
field :body, type: String
field :body_html, type... |
# test_mars_rover.rb
# Tests for Mars Rover Kata
# Author: Jon Simpson <me@jonsimpson.co.uk>
# Date: August 22, 2013
require "./mars_rover"
require "test/unit"
class TestMarsRover < Test::Unit::TestCase
# Tests basic function of the forward command.
def test_forward
rover = MarsRover.new
rover.command('F... |
# Noise
# Horsepower
class Engine
def initialize(sound, horsepower)
@sound = sound
@horsepower = horsepower
end
def move_pistons
@sound
end
end
|
# frozen_string_literal: true
# Copyright (c) 2019 Danil Pismenny <danil@brandymint.ru>
module HandleErrors
extend ActiveSupport::Concern
included do
rescue_from StandardError, with: :handle_error
end
def handle_error(error)
raise error if Rails.env.test?
Bugsnag.notify error if defined? Bugsna... |
# frozen_string_literal: true
require 'active_any/associations/preloader'
require 'active_any/associations/collection_proxy'
require 'active_any/associations/association_scope'
require 'active_any/associations/builder/association'
require 'active_any/associations/builder/singular_association'
require 'active_any/assoc... |
class LikesRule < RankResults::Rule
def apply
@object.tickets_sold * 10
end
end
|
# Stats and stuff, ya know.
class DBLRuby::Stats
# Initialize the stats
# Program does this automatically when running DBLRuby.new.
def initialize(apikey, id)
@api = apikey
@id = id
end
# Get the bot's server count, returns an int.
# @return [Integer] amount of servers the bot is on.
# @raise [DB... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.