text stringlengths 10 2.61M |
|---|
require_relative "customer.rb"
require "csv"
class Order
attr_accessor :products, :customer, :fulfillment_status
attr_reader :id
def initialize(id, products, customer, fulfillment_status = :pending)
@id = id
@products = products
@customer = customer
@fulfillment_status = fulfillment_status
u... |
class Gift < ActionMailer::Base
default from: "Emily Tepper <mail@receiveeverything.com>"
def initiate mystic
attachments['ireceive.mp3'] = File.read(File.join(Rails.root, 'public', 'secretfolder', 'ireceive.mp3'))
mail to: mystic.email
end
end
|
module Ehonda
module Middleware
module Server
module ActiveRecord
class Idempotence
def initialize logger: Shoryuken.logger
@logger = logger
end
def call _worker, queue, sqs_msg, _body
message = TypedMessage.new sqs_msg
if Processed... |
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
has_many :comments, :as => :commentable
def book
return @book if defined?(@book)
@book = commentable.is_a?(Book) ? commentable : commentable.book
end
end
|
# Using Biogem with Rails
class String
# Handle underscore in routing template
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
|
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake'
require 'jeweler'
Jeweler::Tasks.new do |gem|
# gem is a Gem::Specificati... |
# frozen_string_literal: true
# Normalizator::Normalize module
module Normalizator
# Normalization logic for Normalizator
class Normalize
def initialize(rules, data, options)
raise(Normalizator::NormalizeError, 'Nil data') unless data
raise(Normalizator::NormalizeError, 'Nil rules') unless rules
... |
class Artist < ActiveRecord::Base
has_many :events
has_many :venues, :through => :events
# attr_reader :artistID, :artistName, :artistType, :genres
# @@all =[]
# # def initialize( artistID, artistName, genres)
# # @artistID = artistID
# # @artistName = artistName
# # @genr... |
require 'puppet_x/bsd/hostname_if/carp'
describe 'Carp' do
subject(:carpif) { Hostname_if::Carp }
describe 'initialize' do
context 'when minimal configuration is passed' do
it 'should not error' do
expect {
subject.new({
:id => '1',
:device => 'em0',
... |
# Copyright 2011-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
require 'contest'
require 'tilt'
begin
require 'mustache'
raise LoadError, "mustache version must be > 0.2.2" if !Mustache.respond_to?(:compiled?)
module Views
class Foo < Mustache
attr_reader :foo
end
end
class MustacheTemplateTest < Test::Unit::TestCase
test "registered for '.mustache' ... |
require 'rails_helper'
require 'shoulda/matchers'
RSpec.describe Contact, type: :model do
let(:contact) {FactoryGirl.build(:contact)}
let(:created_contact) {FactoryGirl.create(:contact, first_name: 'viji', email: 'viji@gmail.com', age: 27, last_name: 'kumar')}
context 'validations' do
it { should vali... |
class AddArchiveMessages < ActiveRecord::Migration
def self.up
add_column :chat_messages, :archived, :boolean, :default => false
end
def self.down
remove_column :chat_message, :archived
end
end
|
class AddDefaultCategoryForAds < ActiveRecord::Migration
def change
change_column :ads_categories, :category_id, :integer, default: 1
end
end
|
require 'rubygems'
require 'rake'
HAML_GEMSPEC = Gem::Specification.new do |s|
s.name = 'ricogen'
s.rubyforge_project = 'ricogen'
s.summary = "My rails 3 app generator based on hamgen"
s.version = File.read('VERSION').strip
s.authors = ['Hampton Catlin', "David Cuadrado"]
s.email = 'krawek@gmail.com'
s.d... |
after_bundler do
# Get javascript
get_vendor_javascript 'https://raw.github.com/fancyapps/fancyBox/master/source/jquery.fancybox.js', 'jquery.fancybox'
require_javascript 'jquery.fancybox'
# Get images
get_support_file 'app/assets/images/blank.gif'
get_vendor_image 'https://raw.github.com/fancyapps/fancyBo... |
MRuby::Gem::Specification.new('mruby-example') do |spec|
spec.license = 'MIT'
spec.authors = 'your-name'
end
|
require 'delegate'
require 'active_support/core_ext/array/wrap'
require 'hydramata/works/conversions/translation_key_fragment'
require 'hydramata/works/conversions/view_path_fragment'
module Hydramata
module Works
# Responsible for coordinating the rendering of an in-memory data structure
# object to an outp... |
require 'cryptocompare'
class CryptoApiList
def initialize
end
def fetch
list['Data'].reduce([]) do |acc, data|
acc << {
code: data.last['Symbol'], # the API is actually wrong since a symbol should be such as $ € ..
symbol: data.last['Symbol'], # TODO : someday we will add the feature... |
LatoPages::Engine.routes.draw do
root 'back/pages#index'
resources :pages, module: 'back'
scope '/api/v1/' do
get 'fields', to: 'api/v1/fields#index'
get 'fields/:page', to: 'api/v1/fields#index'
get 'fields/:page/:lang', to: 'api/v1/fields#index'
get 'field/:name/:page', to: 'api/v1/fields#sh... |
def with_aws_stubbed(stub_responses_per_service)
require "aws-sdk-core"
stub_responses_per_service.each do |service, stub_responses|
if Aws.config.dig(service, :stub_responses).present?
raise "Aws.config[#{service}][:stub_responses] already set"
else
require "aws-sdk-#{service.to_s.downcase}"
... |
# Some snippets that'll come handy while uploading/naming templates from a rails console.
# Test them once before running, they might get outdated.
class NotificationStringsForKatalon
# This will print all notification strings in the format the Katalon Recorder needs.
# You can filter the output or tweak these comm... |
class ThinkingSphinx::Excerpter
DefaultOptions = {
:before_match => '<span class="match">',
:after_match => '</span>',
:chunk_separator => ' … ' # ellipsis
}
attr_accessor :index, :words, :options
def initialize(index, words, options = {})
@index, @words = index, words
@option... |
class Note < ActiveRecord::Base
validates :body, :track_id, :user_id, presence: true
belongs_to :track,
class_name: 'Track',
foreign_key: :track_id,
primary_key: :id
belongs_to :user,
class_name: 'User',
foreign_key: :user_id,
primary_key: :id
end
|
class Article < ApplicationRecord
has_many :votes
has_many :users, through: :votes
has_one :bias, as: :biasable
attr_accessor :bias_structure, :articles_bias
after_create :retrieve_bias
@articles_bias = Struct.new(:libertarian, :green, :liberal, :conservative)
def self.averages
@articles_bias.ne... |
require 'rails_helper'
RSpec.describe Sport, type: :model do
describe 'validations' do
it 'Requires a sport name' do
sport = build(:sport, name: nil)
expect(sport.valid?).to eq(false)
end
it 'requires that each sport name be unique' do
sport = create(:sport)
sport1 = build(:spor... |
class AccountsController < ApplicationController
before_filter :authenticate_user!
before_filter :get_admin, :only => [:edit, :update, :show, :add_credit, :view_credit, :subscribe, :unsubscribe]
def create
# check if user is admin and have account already
if current_user.type == 'Administrator'
adm... |
class CreatePurchase < ActiveRecord::Migration[5.1]
def change
create_table :purchases do |t|
t.integer :customer_id, :product_id, :merchant_id
t.integer :quantity
t.timestamps null: false
end
end
end
|
class AddTokenToItem < ActiveRecord::Migration
def change
add_column :items, :token, :string
add_column :item_images, :item_token, :string
end
end
|
require '../lib/todolist'
require 'test/unit'
class Testcase < Test::Unit::TestCase
def setup
@t=Todolist.new("pavan.txt")
end
def teardown
@t=nil
end
#testing for empty file
def test_aempty
@t.empty
assert_equal 0,@t.pending.size
assert_equal 0,@t.completed.size
assert_equal 0,@t.list.size
end
#testing for first a... |
require 'spec_helper'
describe Classifier do
before :all do
explanatory_variable :x do
type :numeric
calculate
end
explanatory_variable :y do
type :numeric
calculate
end
end
describe Classifier::SVMachine do
describe "#initialize" do
it "should throw a named ex... |
# -*- coding: utf-8 -*-
class Graph
attr :nodes
def initialize
@nodes=[]
end
def to_s
"##<Graph:0x#{self.object_id.to_s(16)} #{@nodes.each { |n| n.to_s }}>"
end
def add_edge(name1, name2)
node1 = @nodes.find {|n| n.name == name1}
if (node1.nil?)
node1 = Node.new(name1)
@n... |
require 'rails_helper'
RSpec.describe "new book form", type: :feature do
it "displays a form to add a new book - includes title, publication year, pages, cover image (optional), and authors" do
visit new_book_path
fill_in "book[title]", with: "the talisman"
fill_in "book[publication_year]", with: 1984
... |
#
# registrant_fee.rb
# ConstantContact
#
# Copyright (c) 2013 Constant Contact. All rights reserved.
module ConstantContact
module Components
module EventSpot
class RegistrantFee < Component
attr_accessor :id, :amount, :promo_type, :fee_period_type, :type, :name, :quantity
# Factory metho... |
require 'wsdl_mapper/dom/bounds'
module WsdlMapper
module Dom
class Property
class Ref < TypeBase
attr_accessor :containing_type
attr_reader :name, :bounds, :sequence, :default, :fixed, :form
def initialize(name, bounds: Bounds.new, sequence: 0, default: nil, fixed: nil, form: nil)... |
#encoding: utf-8
module Restfuls
class Friends < Grape::API
format :json
helpers FriendHelper
resource 'friend' do
desc '申请好友接口'
params do
requires :session_key,type: String,desc: '会话key'
requires :receiver_id,type: Integer,desc: '接收者id'
end
get '/apply' do
apply
end
post '/ap... |
# frozen_string_literal: true
module OpenVPNStatusWeb
module Parser
class ModernStateless
def self.parse_status_log(text, sep)
status = Status.new
status.client_list_headers = []
status.client_list = []
status.routing_table_headers = []
status.routing_table = []
... |
require 'grape'
require_relative 'janus/all'
require_relative 'terminus/middleware'
require_relative 'veritas/middleware'
require_relative 'hermes/all'
module Engine
class Records < Grape::API
if ENV['RACK_ENV'] != 'test'
use Veritas::Middleware
end
use Janus::Middleware
use Terminus::Middlewa... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Column, type: :model do
context "validations" do
let(:board) { create :board }
let(:valid_params) { { board_id: board.id, name: 'some name' } }
it { expect(described_class.new(board: board)).not_to be_valid }
it { expect(described... |
class UsersController < ApplicationController
before_action :user_instance, only: [:show, :update, :destroy]
def index
@users = User.all
end
def show
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
flash[:succe... |
class TwitchSummoner < ActiveRecord::Base
validates_presence_of :twitch_user, :summoner
validates_uniqueness_of :twitch_user_id, :scope => :summoner_id
belongs_to :twitch_user
belongs_to :summoner
def self.create_by_component(twitch_name, league_name, league_region)
twitch_user = TwitchUser.find_or_crea... |
source 'https://rubygems.org'
# Rails 的版本
gem 'rails', '3.2.13'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
# 資料庫的 gem
gem 'sqlite3'
gem 'haml'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~>... |
# encoding: utf-8
#
# --
# @author zires
#
module OpenQq
# 3.0表示OpenAPI版本, 小数点第二位表示SDK版本
VERSION = "3.0.3"
end
|
FactoryGirl.define do
factory :opendata_member_notice, class: Opendata::MemberNotice do
transient do
site nil
member nil
end
site_id { site.present? ? site.id : cms_site.id }
member_id { member.present? ? member.id : nil }
commented_count 11
confirmed { Time.zone.now }
end
end
|
class ToyRobot
attr_reader :position, :direction, :board
DIRECTIONS = [:north, :east, :south, :west]
COMMANDS = [:place, :move, :left, :right, :report]
def initialize(board)
raise TypeError, 'Invalid board' if board.nil?
@board = board
end
# Places the robot on the board in position X,Y and fac... |
# frozen_string_literal: true
if Rails.env.development? || Rails.env.test?
require 'rspec/core/rake_task'
require 'rubocop/rake_task'
namespace :ci do
desc 'Run specs'
RSpec::Core::RakeTask.new(:specs) do |t|
t.verbose = false
t.rspec_opts = ['--require turnip/rspec',
"-... |
class Membership < ActiveRecord::Base
self.table_name = 'grp_membership'
self.primary_key = :id
alias_attribute :group_id, :grp_id
alias_attribute :user_id, :usr_id
alias_attribute :start_date, :membership_start
alias_attribute :end_date, :membership_end
belongs_to :group, foreign_key: :grp_id
belongs... |
#in these simulations, I will be attempting to follow along with Primer's "Evolution" simulations,
#recreating each one he does, but in text instead of visually.
#Video 1, around 2:13
class Blob
attr_accessor :alive
def initialize(birth_chance, death_chance)
@birth_chance = birth_chance
@death_chance = d... |
# == Schema Information
#
# Table name: quotes
#
# id :integer not null, primary key
# ac26_signed_on :date
# ac2_signed_on :date
# check_number :string
# contract_signed_on :date
# created_by ... |
require 'pry'
def second_supply_for_fourth_of_july(holiday_hash)
# given that holiday_hash looks like this:
# {
# :winter => {
# :christmas => ["Lights", "Wreath"],
# :new_years => ["Party Hats"]
# },
# :summer => {
# :fourth_of_july => ["Fireworks", "BBQ"]
# },
# :fall => {
... |
require 'sinatra'
require 'sinatra/json'
require 'sinatra/activerecord'
set :database_file, 'database.yml'
class Resource < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
end
get '/' do
json Resource.select('id', 'name').all
end
get '/:id' do
resource = Resource.find_by_id(params[:id])
... |
require 'json'
def response(data = nil, opts = {})
if data
opts.merge! body: JSON.dump(data)
opts[:headers] ||= {}
opts[:headers].merge! 'Content-Type' => 'application/json'
end
opts
end
|
require_relative 'node'
class BinarySearchTree
def initialize(root)
@root = root
end
def insert(root, node)
current = root
while true
if node.rating < current.rating
if current.left
current = current.left
else
current.left = node
return
en... |
class CommentsController < ApplicationController
def create
comment = Comment.new comment_params
if comment.save
redirect_to :back
else
flash[:errors] = post.errors.full_messages
redirect_to :back
end
end
def destroy
Comment.find(params[:id]).destroy
redirect_to :back
end
private
def ... |
require "date"
module Models
class Rental
attr_accessor :car
attr_accessor :id, :car_id, :start_date, :end_date, :distance, :deductible_reduction
attr_accessor :transactions
attr_accessor :rental_modifications
# Should be read from config or database, but constants are fine for now
DEDUCTIBL... |
class UsersController < ApplicationController
before_action :authenticate_user!
def show
@bookmarks = current_user.bookmarks.all
@tags = user_tags
@likes = tag_contains_likes
end
def update
if current_user.update_attributes(user_params)
redirect_to edit_user_registration_path, notice: "U... |
class AddMatchIndex < ActiveRecord::Migration
def change
add_index :matches, :match_id
end
end
|
require 'minitest/autorun'
require 'minitest/pride'
require 'csv'
require './lib/transaction-repo'
class TestTransactionRepository < Minitest::Test
def test_we_can_initialize_transactions
data = CSV.read "./data/fixtures/transactions.csv",
headers: true, header_converters: :symbol
t_repo = TransactionRep... |
# == Schema Information
#
# Table name: invoices
#
# id :bigint not null, primary key
# billing_date :date
# number :string
# payment_date :date
# total :float
# your_references :string
# created_at :datetime not null
# updated_at :datetime ... |
class FixturesController < ApplicationController
before_action :authenticate_user!
before_action :set_fixture, only: [:show, :edit, :update, :destroy]
def index
@fixtures = Fixture.all
end
def new
@fixture = Fixture.new
end
def create
Fixture.create(fixture_params)
redirect_to(fixtu... |
module PingPong
class Service
def initialize(match:, victor:)
@match = match
@victor = victor
end
def record!
if @match.finished?
false
elsif !@match.first_service
# This is a rally for service, winner has first serve
@match.first_service_by = @victor
... |
class Indocker::ContextArgs
attr_reader :parent, :name
def initialize(name, context_args, parent, container = nil)
@name = name
@parent = parent
@container = container
@context_args = context_args
end
def method_missing(name, *args)
if args.size > 0
raise ArgumentError.new("context a... |
require 'spec_helper'
describe LocaleFlash::Config do
let(:config) { LocaleFlash::Config }
# Config follows a singleton concept, so ensure goes back to default
# after for every spec.
after { config.template = LocaleFlash::Config::DEFAULT_TEMPLATE }
describe '#template and #template=' do
it 'returns th... |
def recursive_dump(export_path, page)
FileUtils.mkdir_p export_path
unless page.description && page.description.match(/ignore_export/)
puts "exporting #{page.title}"
recursive_path = File::join(export_path, page.title.parameterize)
File.open("#{recursive_path}.yml", 'w') do |out|
page_hash = page.... |
class Connection < ActiveRecord::Base
belongs_to :engine, foreign_key: "engineName", primary_key: "engineName"
default_scope {order(:idconnections => :ASC)}
end |
# frozen_string_literal: true
require 'spec_helper'
class HappyPath
include RailwayOperation::Operator
add_step 0, :step1
add_step 0, :step2
add_step 0, :step3
def step1(argument, **_info)
argument << :step1
end
def step2(argument, **_info)
argument << :step2
end
def step3(argument, **_i... |
class Itpro < ActiveRecord::Base
has_many :tickets
def show_serviced_users
ticket_ids = Ticket.where(itpro_id: self.id, status: 'done').pluck(:user_id)
User.find(ticket_ids)
end
def show_servicing_users
ticket_ids = Ticket.where(itpro_id: self.id, status: 'in_work').pluck(:user_id)
User.find(t... |
class UsersController < ApplicationController
def new
session[:user_id] = nil if logged_in?
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to user_path(@user)
else
@errors = @user.errors.full_messages
... |
#!/usr/bin/env ruby
gem 'minitest', '>= 5.0.0'
require 'minitest/autorun'
require_relative 'code'
class RaindropsTest < Minitest::Test
def test_3
assert_equal 'Pling', Raindrops.convert(3)
end
def test_5
assert_equal 'Plang', Raindrops.convert(5)
end
def test_7
assert_equal 'Plong', Raindrops.... |
require "rails_helper"
RSpec.describe Api::V1::SessionsController, type: :controller do
describe "GET#index" do
before(:each) do
User.create(username: "Penguin", password: "ilovepenguins")
end
it "returns the current user hash when a user is signed in" do
session[:user_id] = 1
response ... |
# https://en.wikipedia.org/wiki/Solitaire_(cipher)
#
# ENCYPTING MESSAGE
# 1. Discard any non A to Z characters, and uppercase all remaining letters.
# Split the message into five character groups, using Xs to pad the last group, if needed.
# 2. Use Solitaire to generate a keystream letter for each letter in the m... |
require_relative '../helper.rb'
describe Later do
let(:redis) { Redis.new db: 15 }
let(:key) { Nest.new 'Events', redis }
describe '.[]' do
it 'returns a schedule with the given key' do
schedule = Later[key]
assert_instance_of Later::Schedule, schedule
assert_equal key, schedule.key
e... |
class Tag < ActiveRecord::Base
attr_accessible :name
# ++++++++++++++++++++
# validation
# ++++++++++++++++++++
validates :name, :presence => true
# ++++++++++++++++++++
# association
# ++++++++++++++++++++
belongs_to :user
belongs_to :article
# ++++++++++++++++++++
# query api
# ++++++++++... |
# 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... |
class RemoveAvatarPathFromContacts < ActiveRecord::Migration[5.1]
def change
remove_column :contacts, :avatar_path, :string
end
end
|
GOOGLE_OAUTH = 'https://accounts.google.com/o/oauth2/auth'
GOOGLE_PARAMS = "?response_type=code&client_id=#{ENV['CLIENT_ID']}"
# Visualizations for Canvas LMS Classes: Teacher login
class CanvasVisualizationAPI < Sinatra::Base
include AppLoginHelper
google_client_id = lambda do
"#{GOOGLE_OAUTH}#{GOOGLE_PARAMS... |
class CreatePropertyDocs < ActiveRecord::Migration
def change
create_table :property_docs do |t|
t.column :name, :string
t.timestamps
end
add_attachment :property_docs, :doc
end
end
|
require_relative '../lib/go_fish_server.rb'
describe 'GoFishServer' do
let(:server) { GoFishServer.new }
let(:clients) { [] }
def create_and_accept_client
client = TCPSocket.new('localhost', server.port_number)
clients << client
server.accept_connection
client
end
before(:each) do
serve... |
# frozen_string_literal: true
module ActionView
module Helpers #:nodoc:
module RecordTagHelper
def div_for(*) # :nodoc:
raise NoMethodError, "The `div_for` method has been removed from " \
"Rails. To continue using it, add the `record_tag_helper` gem to " \
"your Gemfile:\n" \
... |
module XFS
#
# Directory Entry when stored internal to an inode.
# Small directories are packed as tightly as possible so as to fit into the
# literal area of the inode. These "shortform" directories consist of a
# single header followed by zero or more dir entries. Due to the different
# inode number sto... |
class TheBumpCli::Article
attr_accessor :author, :title, :subtitle, :content, :stage
@@all = []
def initialize
@@all << self
end
def self.find_by_stage(stage)
@@all.select {|article| article.stage == stage}
end
def self.new_from_hash(hash)
article = TheBumpCli::Article.new
hash.each do ... |
# encoding: utf-8
require 'pathstring_interface'
require 'pathstring_root'
# we want a string, a little bit more intelligent though, so...
class Pathstring < PathstringInterface
# a little more borrowing from Forwardable
def_delegators :@absolute, :file?, :directory?, :extname, :size, :readlines
# relying on ... |
require 'hamster/versions/ref'
describe Hamster::Versions::Ref do
it("refers an empty hash by default") { expect(subject.deref).to eq Hamster::Hash.empty }
it("dosync creates a new generation") { expect(subject.dosync(name: 'Alvin').deref[:name]).to eq 'Alvin' }
it("older is nil") { expect(subject.older).to be_n... |
class CustomerNeedsController < ApplicationController
before_action :set_customer_need, only: [:show, :update, :destroy]
# GET /customer_needs
def index
@customer_needs = CustomerNeed.all
render json: @customer_needs
end
# GET /customer_needs/1
def show
render json: @customer_need
end
# ... |
# =============================================================================
#
# MODULE : test/test_continuation.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# =============================================================================
... |
module AdminArea::People::Cell
class Show < Show.superclass
# Takes the person, shows their card recommendations. Has a header that
# says 'Recommendation' and a link to add a new rec for the person. If the
# person has any recs, they'll be shown in a <table>. If they don't have
# any, the table will ... |
puts "What is your first name?"
first_name = gets.chomp
puts "What is your middle name?"
middle_name = gets.chomp
puts "What is your last name?"
last_name = gets.chomp
puts "Hello," + first_name.capitalize + middle_name.capitalize + last_name.capitalize + "! Nice to meet you!"
puts "What's your favorite number?"
fave_... |
# frozen_string_literal: true
require_relative '../../../app/api'
require 'rack/test'
require 'ox'
require 'byebug'
module ExpenseTracker
RSpec.describe API do
include Rack::Test::Methods
def app
API.new(ledger: ledger)
end
def json_parsed
JSON.parse(last_response.body)
end
de... |
class FullTextController < ApplicationController
def show
page = params[:page] || 1
search = Etablissement.search do
fulltext params[:id]
paginate page: page, per_page: 10
end
results = search.results
if results.nil?
render json: { message: 'no results found' }, status: 404
... |
require 'rails_helper'
RSpec.feature 'Session', type: :feature do
before :each do
User.create(name: 'john', email: 'john@mail.com')
end
context 'User Login' do
scenario 'Successfully logged in' do
visit new_session_path
fill_in 'Email', with: 'john@mail.com'
click_button 'Login'
expect(page).to hav... |
class Locales < Grape::API
format :json
params do
requires :project, type: String
requires :lang, type: String
requires :namespace, type: String
end
get 'locales/:project/:lang/:namespace' do
GetTranslation.call(permitted_params)
end
params do
requires :project, type: String
requir... |
class AddWatchedFieldToVideoFile < ActiveRecord::Migration
def change
add_column :video_files, :watched, :boolean, default: false
end
end
|
cask 'firefox-custom' do
version "78.0.2"
sha256 'b0896794ae95282946bbe9203083d24cbd2b40768dd5fe1291694dba3bf166a0'
# download-installer.cdn.mozilla.net/pub/firefox/releases was verified as official when first introduced to the cask
url "http://artifactory.generagames.com:8081/artifactory/generic-local/macos/uti... |
require "lucie/log"
module Lucie
module IO
def info message
Lucie::Log.info message
stdout.puts message
end
def debug message
Lucie::Log.debug message
stderr.puts message
end
def error message
Lucie::Log.error message
stderr.puts message
end
def ... |
require 'rails_helper'
RSpec.describe User, type: :model do
before :each do
@user = User.new(
first_name: "first_name",
last_name: "last_name",
email: "email@gmail.com",
password: "password",
password_confirmation: "password",
)
end
describe "Validations" do
it "is... |
# frozen_string_literal: true
describe Facts::Sles::Memory::System::AvailableBytes do
describe '#call_the_resolver' do
it 'returns a fact' do
expected_fact = double(Facter::ResolvedFact, name: 'memory.system.available_bytes', value: 4_900_515_840)
allow(Facter::Resolvers::Linux::Memory).to receive(:r... |
class Phone < ActiveRecord::Base
belongs_to :user
validates_formatting_of :number, using: :us_phone
end
|
# Copyright 2016 OCLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
require 'oj'
require 'typhoeus'
class BTCAccount
def initialize
json_config = Oj.load_file('features/config', Oj.default_options)
@config = json_config
@uuid = @config['BTC']
end
def send_to_account(account, amount)
# uri = URI.parse(@config['URL'])
# header = {'Content-Type': 'application/x... |
#Pseudocode
=begin
INPUT: Obtain a string
STEPS:
CREATE a html_entity hash
entities = {
> => <
< => >
& => &
¢ => ¢
£ => £
¥ => ¥
€ => €
© => ©
® => ®
}
Create a variable called character_array.
Split the string and store it in the character_arr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.