text stringlengths 10 2.61M |
|---|
class Transaction < ApplicationRecord
belongs_to :category
belongs_to :user
has_many :bills
validates :date, presence: true
validates :name, presence: true
# validates :category_id, presence: true
validates :amount, { presence: true, numericality: true }
validates :paid, {inclusion: { in... |
describe 'GITPackCollection' do
before do
@err = Pointer.new(:object)
@collection = GITPackCollection.collectionWithContentsOfDirectory("#{TEST_REPO}/.git/objects/pack", error:@err)
end
should 'not be nil' do
@collection.should.not.be.nil
end
should 'not have an error' do
@err[0].should.be.nil... |
require_relative "../../business/engines/validators"
RSpec.describe Validators::Presence do
describe "#with?" do
context "a nil value" do
subject { described_class.new(:name) }
it "should be invalid" do
expect(subject.with?(nil)).to eql false
end
end
context "an empty string" ... |
# frozen_string_literal: true
def ordinalize(num)
if !num.abs.between?(1, 3)
num.to_s + 'th'
else
case num.abs
when 1 then num.to_s + 'st'
when 2 then num.to_s + 'nd'
when 3 then num.to_s + 'rd'
end
end
end
|
class ControlpltktsController < ApplicationController
before_action :set_controlpltkt, only: [:show, :edit, :update, :destroy]
# GET /controlpltkts
# GET /controlpltkts.json
def index
@controlpltkts = Controlpltkt.all
end
# GET /controlpltkts/1
# GET /controlpltkts/1.json
def show
end
# GET /... |
require 'rspec'
require 'towers_of_hanoi'
describe '#Towers_of_hanoi' do
let (:game) { Towers_of_hanoi.new }
describe '#initialize' do
it 'stacks should contain 3 stacks' do
expect(game.stacks.length).to eq(3)
end
it 'stacks should have three disks' do
expect(game.stacks[1].length).to eq(... |
# encoding: UTF-8
class EEKonto < ActiveRecord::Base
set_table_name "EEKonto"
attr_accessible :ktoNr, :bankId, :kreditlimit
set_primary_key :ktoNr
belongs_to :OZBKonto
belongs_to :Bankverbindung
has_one :ZEKonto, :foreign_key => :ktoNr # Done, getestet
def validate!
errors = ActiveModel::Error... |
class CrabCups
def initialize(cups)
@idx = 0
@len = cups.length
@cups = cups.chars.map(&:to_i)
end
def move
label = cur_label = @cups[@idx]
picks = [@cups[(@idx + 1) % @len], @cups[(@idx + 2) % @len], @cups[(@idx + 3) % @len]]
@cups.reject!{|num| picks.include?(num)}
label = next_cup_... |
# Instructions
# ------------------------------------------------------------------------------
# This file is in the same format as your assessments.
#
# You have 1 hour for this assessment. Give yourself about 15 minutes per problem.
# Move on if you get stuck
#
# Everything should print 'true' when you run the file.... |
class ConcreteHolidays::LaborDay
include ConcreteHolidays::Calculations
def self.date(year) # the first Monday of September
this_or_next(:mon, Date.new(year,9,1))
end
end
|
class CreateTestPapersTestPapers < ActiveRecord::Migration
def up
create_table :refinery_test_papers do |t|
t.integer :wine_id
t.integer :user_id
t.integer :group_id
t.string :score
t.datetime :drink_begin_at
t.datetime :drink_end_at
t.text :note
t.integer :positio... |
class AddFieldsToOrders < ActiveRecord::Migration
def change
add_column :orders, :buyer_id, :integer
add_column :orders, :seller_id, :integer
end
end
|
require "application_system_test_case"
class SharedImagesTest < ApplicationSystemTestCase
setup do
@shared_image = shared_images(:one)
end
test "visiting the index" do
visit shared_images_url
assert_selector "h1", text: "Shared Images"
end
test "creating a Shared image" do
visit shared_imag... |
class AddExchangeRateToDelivery < ActiveRecord::Migration
def up
add_column :deliveries, :exchange_rate, :decimal, :precision => 8, :scale => 2
end
def down
remove_column :deliveries, :exchange_rate
end
end
|
require 'spec_helper'
describe Kuhsaft::TwoColumnBrick, type: :model do
let :two_column_brick do
Kuhsaft::TwoColumnBrick.new
end
describe '#user_can_add_childs?' do
it 'returns false' do
expect(two_column_brick.user_can_add_childs?).to be_falsey
end
end
describe '#user_can_delete?' do
... |
class MoneyAccount < ActiveRecord::Base
# Define the account types like credit cards, line of credit, etc.
ACCOUNT_TYPES = [
{ id: 1, name: 'Cuenta Corriente', credit: false },
{ id: 2, name: 'Inversiones', credit: false },
{ id: 3, name: 'Línea de Crédito', credit: true },
{ id: 4, name: 'Tarjeta ... |
require "application_system_test_case"
class AddtaxisTest < ApplicationSystemTestCase
setup do
@addtaxi = addtaxis(:one)
end
test "visiting the index" do
visit addtaxis_url
assert_selector "h1", text: "Addtaxis"
end
test "creating a Addtaxi" do
visit addtaxis_url
click_on "New Addtaxi"
... |
class UserImagesController < ImagesController
protected
def load_entity
@entity = User.find(params[:user_id])
end
end
|
module ApplicationHelper
end
module Inspirer
class MarkovModel
def initialize
@markov_model = Hash.new { |hash, key| hash[key] = [] }
songs = Song.all
songs.each do |song|
tokens = tokenize(song.lyrics)
until tokens.empty?
token = tokens.pop
markov_state... |
module Entities
class ListEntity < Grape::Entity
expose :id
expose :name
expose :created_at
expose :items, using: Entities::ItemEntity
end
end |
module Api::V1
class ListSerializer < ActiveModel::Serializer
attributes :name, :category
def category
object.category_cd
end
end
end |
class ProductImage < ApplicationRecord
validates_presence_of :image_url, :product_id
belongs_to :product, optional: true
mount_uploader :image_url, ImageUploader
end
|
module DatabaseTheory
class FunctionnalDependency
attr_accessor :determinant, :dependent
# Build a +FunctionnalDependency+ object
# +determinant+:: +String+ object representing the determinant set (comma separated)
# +dependent+:: +String+ object representing the dependent set (comma separated)
def in... |
require 'rails_helper'
RSpec.describe DailyReport, :type => :model do
before do
@daily_report = FactoryGirl.create(:daily_report)
end
subject {@daily_report}
describe "With valid data" do
it "should be valid" do
is_expected.to be_valid
end
it "should respond to date_recieved" do
... |
class AddTagToBills < ActiveRecord::Migration[6.0]
def change
add_column :bills, :tag, :string
end
end
|
class Viewpoints::Acts::Moderateable::ContentDocument < ActiveRecord::Base
include AASM
belongs_to :owner, :polymorphic => true
has_many :content_fields
has_many :content_histories
validate :rejection_requires_code, :codes_requires_rejection
named_scope :filter_status, lambda { |s|
s.b... |
module Typhoid
module Multi
def remote_resources(hydra = nil)
request_queue = RequestQueue.new(self, hydra)
yield request_queue if block_given?
request_queue.run
request_queue.requests.each do |req|
parse_queued_response req
end
end
protected
def parse_queued_... |
class CreateYears < ActiveRecord::Migration
def change
create_table :years do |t|
t.integer :anio
t.timestamps null: false
end
end
end
|
module Gnews
class Client
attr_reader :response
RequestError = Class.new(RuntimeError)
ConfigError = Class.new(RuntimeError)
def call(q:, lang: 'en')
raise ConfigError, 'Missing ENV[GNEWS_SEARCH_URL]' unless config[:GNEWS_SEARCH_URL]
begin
url = build_query_from(q, lang)
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
require 'securerandom'
random_string1 = SecureRandom.hex
random_string2 = SecureRandom.hex
cluster_init_token = "#{random_string1[0..5]}.#{random_string2[0..15]}"
NUM_NODES = 2
NODE_MEM = '4096'
Vagrant.configure('2') do |config|
(1..NUM_NODES).each do |node_number|
nod... |
#!/usr/bin/env ruby
# http://projecteuler.net/problem=5
# Least Common Multiple
def lcm(*numbers)
numbers = numbers.clone
result = 1
divisor = 2
until numbers.empty?
while numbers.any? { |n| n % divisor == 0 }
result *= divisor
numbers.map! { |n| if n % divisor == 0 then (n / divisor) else n e... |
class CreateTexts < ActiveRecord::Migration
def change
create_table :texts do |t|
t.text :text
t.string :lang
t.references :item, :polymorphic => {:default => 'User'}
t.timestamps
end
end
end
|
require 'singleton'
module Pdns
# Domains for reverse DNS
domains = Pdns.config.get_module_config('reverse')['domains'].split(',')
# Subnets
subnets = Pdns.config.get_module_config('reverse')['subnets'].split(',')
default_domain = Pdns.config.get_module_config('reverse')['default_domain']
refresh_tim... |
class CreateAnimees < ActiveRecord::Migration
def change
create_table :animees do |t|
t.string :name
t.timestamps
end
end
end
|
class User < ActiveRecord::Base
devise :database_authenticatable, :recoverable, :rememberable, :trackable,
:registerable
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :games
def self.current
Thread.current[:user]
end
def self.current=(user)
Thread.curr... |
Rails.application.routes.draw do
get '/home', to: 'static_pages#home'
get '/contact', to: 'static_pages#contact'
get '/sponsors', to: 'static_pages#sponsors'
# get '/altronics' load: 'app/assests/images/altronics.png'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/rou... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'archivalSort', type: :system, clean: true do
before do
solr = Blacklight.default_index.connection
solr.add([dog,
cat,
llama,
eagle,
puppy])
solr.commit
visit '/catalog?per_page... |
# require 'yaml_db'
require_relative 'demo/tasks'
require_relative 'demo/setup'
require_relative 'demo/utils'
require_relative 'demo/db'
def demo_branch
fetch(:demo_branch, `git rev-parse --abbrev-ref HEAD`.strip).downcase
end
def demo_host
fetch(:demo_host)
end
def demo_url
format("%s.%s", demo_branch, demo_... |
class RenameColumnAuthId < ActiveRecord::Migration[5.2]
def change
rename_column :books, :auth_id, :author_id
end
end
|
RSpec.feature "BEIS users can download exports" do
let(:beis_user) { create(:beis_user) }
before do
Fund.all.each { |fund| create(:fund_activity, source_fund_code: fund.id, roda_identifier: fund.short_name) }
authenticate! user: beis_user
end
after { logout }
scenario "downloading the actuals for a ... |
require 'rails_helper'
RSpec.feature 'User sees tags on jobs page' do
scenario 'a user can see appropriate tags on jobs page' do
company = Company.create!(name: "ESPN")
job = company.jobs.create!(title: "Developer", level_of_interest: 70, city: "Denver")
tag_1 = job.tags.create!(name:'Software')
tag_... |
module PostsHelper
def post_path(post)
blog_path(post)
end
def cache_key_for_posts
count = Post.count
max_updated_at = Post.maximum(:updated_at).try(:utc).try(:to_s, :number)
"posts/all-#{count}-#{max_updated_at}"
end
end
|
require 'spec_helper'
describe MoneyMover::Dwolla::CustomerFundingSourceResource do
let(:customer_id) { 123987 }
let(:funding_source_id) { 777 }
it_behaves_like 'base resource list' do
let(:id) { customer_id }
let(:expected_path) { "/customers/#{id}/funding-sources" }
let(:valid_filter_params) { [:r... |
class EmployeeSkillsController < ApplicationController
# GET /employee_skills
# GET /employee_skills.json
def index
@employee_skills = EmployeeSkill.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @employee_skills }
end
end
# GET /employee_skills/1
... |
Decanter.config do |config|
# Possible values are :with_exception, true or false
config.strict = :with_exception
end
|
remote_cache = lambda do
cache = fetch(:remote_cache)
cache = deploy_to + "/" + cache if cache && cache !~ /^\//
cache
end
namespace :load do
task :defaults do
set :rsync_exclude, %w[.git*]
set :rsync_include, %w[ ]
set :rsync_options, %w[--archive --recursive --delete --delete-excluded]
se... |
# EventHub module
module EventHub
def self.logger
unless defined?(@logger)
@logger = ::EventHub::Components::MultiLogger.new
@logger.add_device(Logger.new($stdout))
@logger.add_device(
EventHub::Components::Logger.logstash(Configuration.name,
Configuration.environment)
)
... |
# Pick out the minimum age from our current Munster family hash:
ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 5843, "Eddie" => 10, "Marilyn" => 22, "Spot" => 237 }
ages.values.min
# => 10
# #values returns an array of all values from the hash.
# Enumerable#min can be used on an array or hash. It is called on te... |
require_relative "lib/poker_round"
class PokerGame
attr_accessor :file_name, :player_1_score
def initialize(file_name)
@player_1_score = 0
@file_name = file_name
end
def play_game
File.readlines(file_name).each do |line|
result = PokerRound.new(line).play_hand
if result == "Player 1 ... |
class Users::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]
before_filter :verify_is_admin, only: [:admin_edit,:admin_update]
# GET /resource/sign_up
# def new
# super
# end... |
class User < ApplicationRecord
authenticates_with_sorcery!
has_many :decks
has_many :cards
validates_confirmation_of :password
validates :password, presence: true, on: :create
validates :email, presence: true, uniqueness: true
def current_deck
decks.where(current: true).first
end
end
|
class WidgetList::VideoListWidget < AuthorizableWidget
responds_to_event :delete_widget, :with => :destroy
def display
@video_list = options[:widget]
render
end
def destroy(evt)
section = VideoList.find(evt[:widget_id]).section
VideoList.find(evt[:widget_id]).destroy
trigger :widgetDeleted, :s... |
# ../data.img#1772233:1
require_relative '../../lib/dom/dom'
require_relative '../../lib/code_object/base'
describe Dom::Node, "#resolve" do
before do
Dom.clear
@o1 = CodeObject::Base.new
@o2 = CodeObject::Base.new
@o3 = CodeObject::Base.new
@o4 = CodeObject::Base.new
Dom.add_node "Foo... |
class ApplicationMailer < ActionMailer::Base
default from: ENV['MAILER_FROM'] || 'info@makeitreal.camp'
layout 'mailer'
helper ApplicationHelper
def genderize(male, female, user=current_user)
user.gender == "female" ? female : male
end
end
|
class MakeInvLinesDefault < ActiveRecord::Migration[6.0]
def change
InventoryLine.where(quantity_present: nil).update_all(quantity_present: 0)
InventoryLine.where(quantity_desired: nil).update_all(quantity_desired: 0)
change_column_default(:inventory_lines, :quantity_present, from: nil, to: 0)
change_... |
class Api::V1::RevenueController < ApplicationController
def date_range
revenue = RevenueFacade.date_range(params[:start], params[:end])
render json: RevenueSerializer.new(revenue)
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'reviews edit process' do
# need to test with css tag
# it "can take a user to reviews edit page" do
# visit("/shelters/#{@shelter1.id}")
#
# click_link("Edit Review")
#
# expect(current_path).to eq("/reviews/#{@review1.id}/edit")... |
class ChargesController < ApplicationController
def new
@order = Order.find_by(id: session[:order])
end
def create
@order = Order.find_by(id: session[:order])
@amount = @order.stripe_total
customer = Stripe::Customer.create(
email: current_user.email,
card: params[:stripeToken]
)... |
class ChangeLocationModel < ActiveRecord::Migration
def change
remove_column :locations, :state
remove_column :locations, :city
add_column :locations, :location_name, :string
end
end
|
class AddAuthTokenToClients < ActiveRecord::Migration
def up
add_column :clients, :auth_token, :string, limit: 40
add_index :clients, :auth_token, unique: true
Client.all.each do |c|
c.update_attribute :auth_token, SecureRandom.uuid.gsub('-', '')
end
change_column :clients, :auth_token, :s... |
cask 'spek' do
version '0.8.3'
sha256 '648ffe37a4605d76b8d63ca677503ba63338b84c5df73961d9a5335ff144cc54'
# github.com/alexkay/spek was verified as official when first introduced to the cask
url "https://github.com/alexkay/spek/releases/download/v#{version}/spek-#{version}.dmg"
appcast 'https://github.com/ale... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
graalvm_version = "19.0.0"
graalvm_download_url = "https://github.com/oracle/graal/releases/download/vm-#{graalvm_version}/graalvm-ce-linux-amd64-#{graalvm_version}.tar.gz"
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
config.vm.provision "shell", i... |
require 'spec_helper'
describe "User pages" do
subject { page }
describe "index" do
describe "as a regular user" do
let(:user) { FactoryGirl.create(:user) }
before(:each) do
log_in user
visit users_path
end
it { should have_title('Home') }
it { should_not have_h... |
class Wrap < ApplicationRecord
validates :start_time, presence: true, uniqueness: true
validates :precaution_title, length: { maximum: 255 }
validates :precaution_content, length: { maximum: 255 }
validate :date_before_today
def date_before_today
if start_time.present? && start_time > Date.today
er... |
get "/students/new" do
erb :"students/new"
end
post "/students" do
@student = Student.new(params[:student])
if @student.save
redirect "/sessions/new"
else
@errors = @student.errors.full_messages
erb :"students/new"
end
end
get "/students/:id" do
if logged_in?
@student = Student.find(params... |
require "aws-sdk"
module Snapshotar
module Storage
##
# This snapshot storage type connects to amazon s3 via *aws-sdk gem*.
class S3Storage
def initialize #:nodoc:
raise ArgumentError, "You should set ENV['AWS_ACCESS_KEY_ID'] to a valid value" unless ENV['AWS_ACCESS_KEY_ID']
rais... |
class Home_placeholder
def id
"0"
end
def name
"Homepage"
end
end
|
#!/usr/bin/env ruby
#
# Passcode derivation
# http://projecteuler.net/problem=79
#
# A common security method used for online banking is to ask the user for three
# random characters from a passcode. For example, if the passcode was 531278, they
# may ask for the 2nd, 3rd, and 5th characters; the expected reply would b... |
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :web_link
attr_accessible :body
after_create :remove_archives
validates :body, :presence => true
private
# If a comment gets added, then it should be unarchived for both people.
def remove_archives
self.web_link.archive_links.each... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
before_action :track_user
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
end
def self.default_url_options(options={})
options.merge({ :locale => I18n.locale })... |
require 'cloudinary'
require 'redis'
require 'slack-ruby-bot'
if ENV["RACK_ENV"] != "production"
require 'pry'
end
module Bot
REDIS_CONN = Redis.new(:url => ENV["REDIS_URL"] || "redis://localhost:6379")
class App < SlackRubyBot::App
end
class PicAdd < SlackRubyBot::Commands::Base
command 'pic add'
... |
class OutcomesController < ApplicationController
def new
@outcome = Outcome.new
end
def create
@outcome = Outcome.new(outcome_params)
if @outcome.save
redirect_to @outcome
else
render 'new'
end
end
def show
@outcome = Outcome.find(params[:id])
end
def index
@outcomes = Outcome.all
end
... |
require 'test_helper'
class TestScoresControllerTest < ActionController::TestCase
setup do
@test_score = test_scores(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:test_scores)
end
test "should get new" do
get :new
assert_response :s... |
class AuctionSerializer < ActiveModel::Serializer
attributes :id, :title, :description, :price, :end_date, :created_at
belongs_to :user, key: :seller
has_many :bids
def created_at
object.created_at.strftime('%Y-%B-%d')
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: taggings
#
# id :integer not null, primary key
# tag_id :integer not null
# data_table_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
req... |
require 'rails_helper'
RSpec.describe Store, type: :model do
before do
@store = build(:store)
end
it "有効なstoreを持つこと" do
expect(@store).to be_valid
end
it "store_manager_idがなければ無効であること" do
@store.store_manager_id = nil
expect(@store).to be_invalid
end
describe 'stoer_name' do
it "お店の... |
class CustomerOrdersController < ApplicationController
before_action :set_customer_order, only: [:show, :edit, :update, :destroy]
# GET /customer_orders/1
# GET /customer_orders/1.json
def show
end
# GET /customer_orders/new
def new
@customer_order = CustomerOrder.new
@gig = Gig.friendly.find(pa... |
class AddCalculatorClassToShipMethod < ActiveRecord::Migration
def change
add_column :ship_methods, :calculator_class, :string, null: false, limit: 256
end
end
|
Fabricator :vino do
nombre { Faker::Lorem.words(2).join }
end |
describe FalseClass do
before { allow(self).to receive(:foo) }
describe '#if_true' do
before { false.if_true { self.foo } }
it { expect(self).not_to have_received(:foo) }
end
describe '#if_false' do
before { false.if_false { self.foo } }
it { expect(self).to have_received(:foo).once }
end
en... |
module Motion
module SettingsBundle
class Configuration
attr_reader :preferences, :children
def initialize(&block)
@preferences = []
@children = {}
block.call(self)
end
def text(title, options = {})
preference(title, "PSTextFieldSpecifier", options, {
... |
module Api
module Endpoints
class TeamsEndpoint < Grape::API
format :json
helpers Api::Helpers::CursorHelpers
helpers Api::Helpers::SortHelpers
helpers Api::Helpers::PaginationParameters
namespace :teams do
desc 'Get a team.'
params do
requires :id, type: S... |
class TimingsController < ApplicationController
# GET /timings
# GET /timings.xml
def index
@timings = Timing.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @timings }
end
end
# GET /timings/1
# GET /timings/1.xml
def show
@timing = Timin... |
class SonicScrewDriverSerializer < ActiveModel::Serializer
attributes :id, :image, :description, :link
has_one :doctor
end
|
class Tracker < ActiveRecord::Base
validates :keyword, presence: true, length: { minimum: 3 }
end
|
# frozen_string_literal: true
class DeleteAccountJob < ApplicationJob
def perform(account_id)
return unless Account.where(id: account_id).exists?
account = Account.find(account_id)
Account.transaction do
account.tails.delete_all
account.comment_logs.delete_all
account.api_vk_error_log... |
require 'sinatra'
require 'grape'
module Springseed
class API < Grape::API
version 'v1', vendor: 'springseed'
format :json
Dir.glob('apis/**/*.rb') { |n| load n }
end
end
|
class Movie < ActiveRecord::Base
image_accessor :cover_image
validates :name, :presence => true, :uniqueness => true
validates :cast, :presence => true
has_many :keywords, :dependent => :destroy do
def query_twitter
collect(&:perform_search).reduce(0, :+)
end
end
has_many :tweets, :depend... |
class PaymentTypesController < ApplicationController
respond_to :json
before_filter :authorize
before_action :find_company , :only =>[:index , :new , :create ]
before_action :get_payment_type , :only =>[:edit , :update , :destroy ]
def index
payment_types = @company.payment_types.select("id , n... |
class CreatePia < ActiveRecord::Migration
def change
create_table :pia, id:false, primary_key: :pid do |t|
t.string :pid
t.string :titulo
t.string :cie_9
t.string :informacion
t.string :normativa
t.string :normativa_url
t.string :snomed
t.string :ancestry
end ... |
require 'spec_helper'
describe 'nginx', :type => :class do
let (:facts) { debian_facts }
let (:pre_condition) { '$concat_basedir = "/tmp"' }
let (:params) { { :config_dir => '/etc/nginx' } }
describe 'without parameters' do
it { should create_class('nginx') }
it { should include_class('nginx::install'... |
require 'test_helper'
class OrderNotifierTest < ActionMailer::TestCase
test "received" do
mail = OrderNotifier.received(orders(:mail))
assert_equal "Book store order confirmation", mail.subject
assert_equal ["test@example.com"], mail.to
assert_equal ["me@fadhb.com"], mail.from
#assert_match /1 x ... |
######################## Numbers to digits ########################
def number_to_digits(n)
n.to_s.chars.map(&:to_i)
end
######################## Digits to numbers ########################
def digits_to_number(digits)
digits.reduce(0) { |a, b| a * 10 + b }
end
def digits_to_number_2(array)
new_number = 0
a... |
require 'aws-sdk-s3'
module Stax
module Aws
class S3 < Sdk
class << self
def client
@_client ||= ::Aws::S3::Client.new
end
def list_buckets
client.list_buckets.buckets
end
def bucket_tags(bucket)
client.get_bucket_tagging(bucket: buc... |
class DeliveriesItemsController < ApplicationController
respond_to :json
def index
respond_with DeliveriesItems.all
end
end
|
class Product < ActiveRecord::Base
default_scope { order('title') }
has_many :line_items
has_many :orders, :through =>:line_items
before_destroy :ensure_not_referenced_by_any_line_item
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present'... |
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :exercise
scope :get_error_comment_by_admin, -> {joins(:user).where("role not in ('developer', 'root', 'admin') and status = 0").order(created_at: :desc)}
scope :get_done_comment_by_admin, -> {joins(:user).where("role not in ('developer', 'root', '... |
class User < ActiveRecord::Base
has_many :flowers
has_many :comments
has_many :ratings
has_secure_password # has before save shit to encrypt pw?
valid_email = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: valid_email }, uniqueness: { case_sensitive: false }
validates :p... |
Rails.application.routes.draw do
resources :partners
resources :customers
resources :friends
#get 'home/index'
root 'home#index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
|
module Spree
module PaymentDecorator
def verify!(**options)
process_verification(options)
end
private
def process_verification(**options)
protect_from_connection_error do
response = payment_method.verify(source, options)
record_response(response)
if response.suc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.