text stringlengths 10 2.61M |
|---|
module ApplicationHelper
def render_question_info(question)
case question.question_type
when 1
"Please select on of the following answer that you think is correct"
when 2
"You be able to select one or more correct answers"
else
""
end
end
end
|
class CreateResidues < ActiveRecord::Migration[5.0]
def change
create_table :residues do |t|
t.string :name
t.string :kind
t.string :blend
t.string :onu
t.string :code
t.belongs_to :laboratory, index: true, foreign_key: true
t.belongs_to :collection, index: true, foreign_... |
json.comments @review.comments
json.star_rating star_rating(@review.rating)
json.restaurant do
json.id @restaurant.id
json.review_count pluralize(@restaurant.reviews.count, 'review')
json.average_rating @restaurant.average_rating
json.average_rating_stars star_rating(@restaurant.average_rating)
end
|
class AddEmailToLeadsForm < ActiveRecord::Migration[5.1]
def change
add_column :leads, :Email, :string, :after => :Business
end
end
|
#!/usr/bin/env ruby
# Stitch transcriptions.
# Report timings: Uzbpart-21/UZB_999_999.wav UZB_999_999.wav sampleBgn sampleEnd
#
# Source data is described in PTgen/test/2016-08-24/a.txt.
#
# .wav's listened to by turkers:
# /workspace/speech_web/uzbek/splitUZB/* 6.8 GB (flacs and wavs. Use soxi to get durations.)
... |
# -*- encoding : utf-8 -*-
class Exhibition < ActiveRecord::Base
belongs_to :category
has_many :pictures, :as => :pictureable, :dependent => :destroy
has_many :pdfs, :as => :pdfable, :dependent => :destroy
# attr_accessor :crop_medium_x, :crop_medium_y, :crop_medium_width, :crop_medium_height, :crop_thumb_x, :... |
require 'spec_helper'
describe UsersController do
login_admin
let(:user) { subject.current_user }
describe "GET #profile" do
before { get :profile }
it { should assign_to(:user).with user }
it { should respond_with :success }
it { should render_template :profile }
end
end
|
class RequestsController < ApplicationController
def index
@requests = Request.all.order(:name)
#This is inefficient, but will be OK for a small number of requets
@passing = []
@failing_high = []
@failing_low = []
@requests.each do |request|
if request.status
@passing << re... |
require 'test_helper'
class Web::Admin::HashTagsControllerTest < ActionController::TestCase
setup do
admin = create :admin
sign_in admin
@hash_tag = create :hash_tag
@exceptions_attributes = ['id', 'created_at', 'updated_at', 'published_at']
end
test 'should get index' do
get :index
asse... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
ratyrate_rater
ratyrate_rateable 'note_user'
acts_as_commentable
has_many :products, foreign_key: "user_id", dependent: :destroy
has_many :bids, foreign_key: ... |
class EconomicParameterValuesController < ApplicationController
# GET /economic_parameter_values
# GET /economic_parameter_values.json
def index
@economic_parameter_values = EconomicParameterValue.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @economic_par... |
class SingleVirtualProduct < VirtualProduct
belongs_to :tuan, :counter_cache => :max_amount
after_save :change_max_amount,:unless=>Proc.new{|product| product.tp == 0}
def type_name
"单用户"
end
def buy(user_id,order_item_id)
return if user_id.blank?
if self.tp==0
self.sell_out
Virtu... |
require 'jindouyun/dingding/sns_app_account/api'
module Jindouyun::Dingding
module SnsAppAccount
# Required fields:
# reader only:
# * app_id
# * app_secret
# reader and writer:
# * sns_access_token
# * sns_access_token_expired_at
BASE_URL = 'https://oapi.dingtal... |
require 'rails_helper'
RSpec.describe Chatroom, type: :model do
context 'validation' do
after(:each) do
Chatroom.destroy_all
end
after(:all) do
Message.destroy_all
end
it 'should validate name presence' do
chatroom = Chatroom.new()
chatroom.validate
expect(chatroom... |
class AddRobotToUser < ActiveRecord::Migration[5.2]
def change
add_column :users, :not_a_robot, :boolean, default: false
end
end
|
# Part 1: Object Models
# Create a lib directory and put the classes you create in there.
# Create a Class for song, artist, and genre. Use an individual file for each class.
# These files should be placed within a lib directory and required on the top of
# any script that utilizes them (including this test script). O... |
#
# Exception redirection module
#
# @author [nityamvakil]
#
module Errors
extend ActiveSupport::Concern
# include Exceptions
def self.included(base)
base.rescue_from Exception, with: :render_server_error
base.rescue_from Net::OpenTimeout, with: :render_gateway_timeout
base.rescue_from ArgumentError,... |
class Manager::Survey::QuestSerializer < ActiveModel::Serializer
root false
attributes :id, :order, :content, :qtype
has_many :choices, serializer: Manager::Survey::ChoiceSerializer
end
|
class CreateUserPalettes < ActiveRecord::Migration[6.0]
def change
create_table :user_palettes do |t|
t.string :background_color
t.string :font_color
t.string :font_family
t.belongs_to :user, null: false, foreign_key: true
t.timestamps
end
end
end
|
module HomeHelper
def has_twitter?
has_social_network? "twitter"
end
def has_linkedin?
has_social_network? "linkedin"
end
def has_googleplus?
has_social_network? "google_oauth2"
end
def has_facebook?
has_social_network? "facebook"
end
def has_github?
has_social_network? "github"
end
def facebook_... |
Rails.application.routes.draw do
root to: 'web/welcome#index'
scope module: :web do
namespace :admin do
root to: 'welcome#index', as: ''
resources :articles
resources :events
resources :banners
resources :users
resources :videos
resources :hash_tags
resources :ins... |
module Discovery
class Category < ActiveRecord::Base
attr_accessible :name, :personality_id, :career_id, :major_ids
# Relationships
belongs_to :personality
has_many :major_recommendations
has_many :majors, through: :major_recommendations
has_many :career_recommendations
has_many :careers, t... |
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2013, Brian Lopez
# Copyright (c) 2013, Sebastian Staudt
module RBzip2::FFI
DEFAULT_BLK_SIZE = 3
BZ_RUN = 0
BZ_FLUSH = 1
BZ_FINISH = 2
BZ_... |
# Copyright 2014 Square 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
#
# Unless required by applicable law or agreed ... |
class AddPost1IdToUserBookPages < ActiveRecord::Migration
def self.up
add_column :user_book_pages, :post1_id, :integer
add_column :user_book_pages, :post2_id, :integer
add_column :user_book_pages, :post3_id, :integer
end
def self.down
end
end
|
require 'spec_helper'
describe Buckaroo::Ideal::Request do
let(:order) { Buckaroo::Ideal::Order.new }
let(:request) { Buckaroo::Ideal::Request.new(order) }
before do
Buckaroo::Ideal::Config.configure(
:merchant_key => 'merchant_key',
:secret_key => 'secret_key',
:test_... |
class FavoritesController < ApplicationController
def create
@post = Post.find(params[:post_id])
favorite = current_user.favorites.build(post: @post)
authorize favorite
if favorite.save
flash[:notice] = "Favorite saved"
redirect_to [@post.topic, @post]
else
flash[:error] = "There was an error saving favori... |
class Animal
attr_reader :color
def initialize(color)
@color = color
end
end
class Cat < Animal
end
class Bird < Animal
end
cat1 = Cat.new('Black')
cat1.color
# Using the following code, determine the lookup path used when invoking cat1.color.
# Only list the classes that were checked by Ruby when searc... |
require 'user'
describe User do
describe '#user_balance' do
it 'shows the user their starting balance of £0' do
expect(subject.user_balance).to eq(0)
end
end
describe '#user_deposit' do
it 'allows sum to be deposited into user account' do
amount = 500
expect { subject.user_deposit(... |
require 'rails_helper'
RSpec.describe FriendsController, type: :controller do
describe '.handle_success' do
it 'renders the friends to the view' do
friends = [FriendEntity.new(name: 'Bob', image_url: 'foo', id: 1)]
subject.handle_success(friends)
expect(assigns(:friends)).to equal(friends)
... |
class Api::TasksController < ApplicationController
def update
task = Task.find(params[:id])
if task.update(task_params)
render json: task
end
end
private
def task_params
params.require(:task).permit(:done)
end
end
|
module XboxHelper
def xbox_boolean(value, size='2x')
fa_icon "#{value ? 'check-' : ''}square-o #{size}", class: (value ? 'green' : 'gray')
end
def online_multiplayer(min, max)
if (min.nil? || min < 1) && (max.nil? || max < 1)
'None'
else
str = ''
str << "#{min}" if (!min.nil? || min... |
class Logster < DebianFormula
url 'https://github.com/etsy/logster.git',
:tag => 'cc0eb8e44f739a589779ebbf2dfcc92e498fe37e'
homepage 'https://github.com/etsy/logster'
name 'logster'
version '0.0+github1'
section 'utils'
description 'Parse log files and generate metrics for Graphite and Ganglia'
dep... |
json.boards do
json.byId do
@boards.each do |board|
json.set! board.id do
json.extract! board, :id, :name, :shared, :author_id
end
end
@shared_boards.each do |board|
json.set! board.id do
json.extract! board, :id, :name, :shared, :author_id
end
end
end
js... |
require_relative '../../../../spec_helper'
describe 'icinga::contact_group', :type => :define do
let(:title) { 'jims_friends' }
let(:params) {{ "group_alias" => "Awesome Team", "members" => [ 'jim', 'bob' ]}}
it { is_expected.to contain_file('/etc/icinga/conf.d/contact_group_jims_friends.cfg').
with_content(... |
module Users
class BankCard < ActiveRecord::Base
CARD_TYPE = [DEBIT_CARD = 0, CREDIT_CARD = 1]
validates_inclusion_of :card_type, in: CARD_TYPE
attr_accessible :card_number, :credit_earned, :cashing_card
belongs_to :user
def self.is_cashing_card
where(cash_card: true)
end
end
end
|
class ApiTokenPolicy
include ExceptionPolicy
# ApiTokenPolicy is odd in that it doesn't _have_ a user; we're really just
# validating the params, so that will play the role of "user" here. Further,
# we'll be determining the api_token from the params, so the second variable
# here is not used
def initializ... |
# encoding: UTF-8
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
begin
require 'rspec/core/rake_task'
desc "Run specs"
RSpec::Core::RakeTask.new do |t|
t.rspec_opts = %w(--color) + %w[-fs]
# t.ruby_opts = %w(-w)
end
... |
module Qualtrics::API
class User < BaseModel
attribute :id
attribute :username
attribute :first_name
attribute :last_name
attribute :user_type
attribute :division_id
attribute :status
attribute :language
# attribute :permissions
attribute :organization_id
attribute :unsubsc... |
class ParticipationsController < ApplicationController
def index
policy_scope(Participation)
@participations = Participation.all.order("created_at DESC")
@events = Event.all
end
def show
@participation = Participation.find(params[:id])
authorize @participation
@event_id = @participatio... |
class Libksba < Package
desc "A library to access X.509 certificates and CMS data"
homepage "https://github.com/gpg/libksba"
url "https://www.gnupg.org/ftp/gcrypt/libksba/libksba-${version}.tar.bz2"
release version: '1.3.5', crystax_version: 1
depends_on 'libgpg-error'
build_copy 'COPYING', 'COPYING.GPL... |
# frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rubygems'
require 'ncmb'
require 'yaml'
yaml = YAML.load_file(File.join(File.dirname(__FILE__), '..', 'setting.yml'))
NCMB.initialize(application_key: yaml['application_... |
class BusinessUsersController < ApplicationController
before_filter :authenticate_user!, :business_default_values
load_and_authorize_resource
def new
if BusinessPost.create(params[:business_post])
flash[:notice] = "Se ha creado una nueva promocion"
end
render :index
end
private
def bu... |
class FontDigohweliOldDo < Formula
head "https://www.languagegeek.com/font/OldDODigohweli.zip"
desc "Digohweli Old DO"
homepage "https://www.languagegeek.com/font/fontdownload.html"
def install
(share/"fonts").install "OldDODigohweli.ttf"
end
test do
end
end
|
FactoryGirl.define do
factory :user do |f|
sequence(:goodreads_id) {|i| i.to_s }
library_system_ids { [LibrarySystem::MINUTEMAN.id] }
end
end
|
class SectionsController < ApplicationController
def new
@user = User.find(params[:id])
@schedule = @user.schedules.find(params[:schedule_id])
@section = Section.new
end
def create
@user = User.find(params[:id])
@schedule = @user.schedules.find(params[:schedule_id])
@section = Section.new(section_param... |
class FontMarckScript < Formula
head "https://github.com/google/fonts/raw/main/ofl/marckscript/MarckScript-Regular.ttf", verified: "github.com/google/fonts/"
desc "Marck Script"
homepage "https://fonts.google.com/specimen/Marck+Script"
def install
(share/"fonts").install "MarckScript-Regular.ttf"
end
te... |
require 'test_helper'
ANY_ASIN = '1430218150'
class TestAsin < Test::Unit::TestCase
def setup
@helper = Object.new
@helper.extend ASIN
end
def test_lookup_with_configured_asin
secret = ENV['ASIN_SECRET']
key = ENV['ASIN_KEY']
puts "configure #{secret} and #{key} for this test"
@he... |
###
# Adiciona Callbacks do Plugin Subtasks
###
module RedmineSubtasks
class Hooks < Redmine::Hook::ViewListener
# hook view_layouts_base_body_bottom chamado no layout base depois de renderizado o conteúdo antes do footer
# nesse caso é utlizado para substituir a arvore de subtarefas pela outra construida na p... |
# encoding: UTF-8
#--------------------------------------------------------------------------------------------------------------------------------
#
# [MODULE] Wanok
#
# Some methods.
#
#--------------------------------------------------------------------------------------------------------------------------------
m... |
class MessagesController < ApplicationController
# Probably wont use this - quicker to send and receive on the websocket channel
before_action :authenticate_user!
def index
render '/messages/index'
end
def create
message = Message.new(message_params)
if message.save
ActionCable.server.broa... |
require 'open-uri'
require 'nokogiri'
class BooksController < ApplicationController
# GET /books
# GET /books.json
def index
if params[:search]
@books = Book.find(:all, :conditions => ['title LIKE ? OR isbn LIKE ? OR authors LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
root 'clients#landing_page', via: [:post, :get]
get 'clients', to: 'clients#index'
get 'permission_denied', to: 'clients#permission_denied'
end
|
#Given an array of integers, sort the array into a wave like array and return it,
#In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5.....
#Given [1, 2, 3, 4] => One possible answer : [2, 1, 4, 3]
class Solution
# param a : array of integers
# return a array of integers... |
class User < ApplicationRecord
has_many :sitters, through: :favorites
has_many :photos
has_many :pets
has_many :sit_pets
has_many :favorites
has_many :ratings
attachment :picture
accepts_nested_attributes_for :sit_pets
geocoded_by :full_street_address # can also be an IP address
after_validation... |
class Post < ActiveRecord::Base
default_scope { order('created_at DESC') }
before_save :titleize_title, :get_slug
validates_presence_of :title, :content
def self.recent
self.order(created_at: :desc)
end
private
def titleize_title
self.title = title.titleize
end
def get_slug
self.slug... |
require 'set'
class SetOfRanges::Set < Set
def add(obj)
raise ArgumentError if obj.nil?
raise ArgumentError unless obj.is_a? Range
rng = obj.exclude_end? ? (obj.begin..(obj.end-1)) : obj
if empty?
super(rng)
else
overlapping_ranges = Set.new
each do |r|
if r.begin <= ... |
class CreateDistricts < ActiveRecord::Migration[5.0]
def change
create_table :districts do |t|
t.string :name
t.string :permalink
t.string :lat
t.string :lng
t.timestamps
end
add_index :districts, :name, unique: true
add_index :districts, :permalink, unique: true
end
... |
class AppointmentsController < ApplicationController
before_filter :collaborator_authorized, :only => [:new, :create]
before_filter :require_user
def index
@customes = current_user.customers
end
def new
@customer = current_user.my_customers.find(params[:customer_id])
@appointment = @customer.ap... |
module ProfileGraphHelper
def build_area_graph_data_with_quota(processed_requests, rejected_requests)
[
{
name: t('views.profile.show_api_use.request_distribution.under_quota_requests'),
data: processed_requests.map do |requests|
[requests['key'], requests['doc_count']]
en... |
# frozen_string_literal: true
# Advent of Code 2020
#
# Robert Haines
#
# Public Domain
require 'aoc2020'
module AOC2020
module Extra
module CLI
HEADER = 'Advent of Code 2020: '
def self.parse_params(argv)
return false if argv.empty?
argv.map(&:to_i).each do |day|
return... |
require 'erb'
require 'optparse'
require 'fileutils'
require_relative 'optboot/compiler'
require_relative 'optboot/generator'
require_relative 'optboot/version'
module OptBoot
module_function
def parse_options(argv)
options = {
dataout: 'data.bin',
exeout: 'optimized',
base: '',
opt: ... |
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
get "/users/verify", to: 'users#verify'
post "/users/login", to: 'users#login'
resources :users do
resources :posts
end
get "/posts", to: 'posts#all'
get "/comments",... |
# == Schema Information
#
# Table name: responses
#
# id :integer not null, primary key
# answer_id :integer not null
# user_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class Response < ApplicationRecord
valid... |
class TodoScreen < PM::TableScreen
title "Todo"
refreshable
def on_load
set_nav_bar_button :right, system_item: :add, action: :add
@data = []
load_data
end
def load_data
# 默认每页20条
Task.where(:status=>0).sort(:createdAt=>:desc).page(1).find do |tasks, error|
if !error
... |
class Doi < ActiveRecord::Base
belongs_to :user
has_many :reviews, dependent: :destroy
has_many :urls, dependent: :destroy
validates :name, :description, presence: true
end
|
module ManagementConsultancy
module Admin
class UploadsController < ManagementConsultancy::FrameworkController
skip_before_action :verify_authenticity_token, only: :create
before_action :authenticate_user!
before_action :authorize_user
def index
@back_path = :back
@uploads... |
require_relative 'class/class'
require_relative 'instance/instance'
class Structus; class << self
# @group Constructor
alias_method :new_instance, :new
private :new_instance
# @param [Symbol, String] *names
# @return [Class] - with Subclass, Subclass:Eigen
def new(*names, &block)
::Class.new(self... |
class AddEventActivitiesToEvents < ActiveRecord::Migration
def change
add_column :events, :event_activities, :string
end
end
|
Trestle.configure do |config|
config.site_title = "El Boarding"
config.reload = :always
config.auth.user_class = -> { Administrator }
config.auth.user_admin = -> { :"auth/administrators" }
end
|
def solve( problem )
lines = problem.split(".")
names = lines.first.scan( /[A-Z]\w*/ )
re_names = Regexp.union( names )
# Later on, search for these keywords (the word "not" is handled separately).
words = %w(first second third fourth fifth sixth seventh eighth nineth tenth
bottom top higher lower adjacent)... |
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Tikkie::Notification do
context 'with a bundle notification' do
let(:body) { File.read('spec/fixtures/notifications/bundle.json') }
describe '.parse' do
it 'returns a bundle notification' do
notification = described_class.pars... |
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# provider :string(255)
# uid :string(255)
# name :string(255)
# image :string(255)
# token :string(255)
# expires_at :datetime
# created_at :datetime
# updated_at :datetime
# bill_id ... |
# programa de conta corrente
# deve ter um método de depósito
# deve ter um método de saque
class Conta
attr_accessor :nome, :saldo, :mensagem
def initialize(nome, saldo)
self.nome = nome
self.saldo = saldo
end
def deposita(valor)
self.saldo =+ valor
end
def saca(v... |
class Medication < ActiveRecord::Base
has_many :patients
validates :name, :dosage, :schedule, :starts_on, :ends_on, :patient_id, :presence => true
end |
require 'rack/urlmap'
class GameResult
def self.app
self.new.routes
end
def routes
Rack::URLMap.new(
'/api/results' => results,
'/dist' => public_files,
'/' => index_path
)
end
private
HTML = { 'Content-Type' => 'text/html' }.freeze
def public_files
Proc.new do |env|... |
# Prompts the user for two integesteps.
# - The first one should be between 1 and 4, with
# * 1 meaning initially looking North,
# * 2 meaning initially looking East,
# * 3 meaning initially looking South,
# * 4 meaning initially looking West.
# - The second one should be positive. When written in base 3, its c... |
module Images
class GetUploadAttrs
attr_reader :direct_upload_url
def initialize(direct_upload_url)
@direct_upload_url = direct_upload_url
end
def call
tries ||= 5
direct_upload_url_data = Image::DIRECT_UPLOAD_URL_FORMAT.match(direct_upload_url)
aws_client = Aws::S3::Client.n... |
require 'test_helper'
class BearsInstancesControllerTest < ActionDispatch::IntegrationTest
def setup
@user = users(:tomas)
@other_user = users(:archer)
end
# Index
test "should redirect index when not logged in" do
get bears_instances_path
assert_redirected_to login_url
... |
class Array
def where(options)
self.select do |item|
criteria_met = 0
# tally how many criteria are met
options.each do |key, value|
if value.is_a? Numeric # for rank (exact) match criterium
criteria_met += 1 if item[:rank] == value
elsif value.is_a? String # for text e... |
class BankTransaction < ApplicationRecord
REVERSAL_SUCCEED_NOTICE = "\n TRANSACTION REVERSED"
REVERSAL_FAILED_NOTICE = "\n TRANSACTION REVERSAL FAILED"
NSF_NOTICE = "\n INSUFFICENT FUNDS, NO EXCHANGE MADE"
scope :latest, -> { order(updated_at: :desc) }
belongs_to :from_account, class_name: 'BankAccount'
b... |
class RequestPolicy < ApplicationPolicy
def create?
true
end
def new?
create?
end
def show?
@user.admin? || @user.all_organizations.map(&:id).include?(@record.organization_id)
end
def edit?
return false if @record.archived_proxy?
return true if @user.admin?
return false if @reco... |
class CreateEmployees < ActiveRecord::Migration[5.1]
def change
create_table :employees do |t|
t.integer :emp_id
t.text :first_name
t.text :last_name
t.date :date_of_birth
t.text :salary
t.text :email
t.text :phone
t.text :email
t.timestamps
end
end
end... |
class User < ApplicationRecord
has_many :sns_credentials, dependent: :destroy
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable,
... |
class AddWordPhonetic < ActiveRecord::Migration
def change
add_column :words, :phonetic_uk, :string, length: 128
add_column :words, :phonetic_en, :string, length: 128
end
end
|
class AnswerViewController < UIViewController
attr_accessor :index
attr_accessor :state
attr_accessor :questionLabel
def viewDidLoad
super
self.questionLabel = UILabel.alloc.initWithFrame(CGRectMake(0, 0, 0, 0)).tap do |label|
label.text = UIApplication.shared... |
class WelcomeController < ApplicationController
before_action :authenticate_user
def show
puts "#" * 60
puts "Welcome controller required to GET show.html.erb from welcome view, with dynamic URL variable" #récupérer la valeur contenue dans l'URL - à l'endroit où on a initialisé la variable dans un GET (i.e... |
require 'spec_helper'
describe ShopifyImport::DataParsers::Payments::BaseData, type: :service do
let(:shopify_transaction) { create(:shopify_transaction) }
subject { described_class.new(shopify_transaction) }
describe '#payment_number' do
it 'creates number with transaction id' do
expect(subject.payme... |
# console menu command methods for class Route
module MenusRoutes
private
def show_routes(arr = @routes)
raise ArgumentError, '=> Маршрутов нет' if arr.empty?
arr.each.with_index(1) { |r, i| puts "#{i}. Маршрут #{route_info(r)}" }
rescue ArgumentError => e
puts e.message
end
def rou... |
require 'cf_spec_helper'
require 'language_pack/ruby_semver_version'
describe LanguagePack::RubySemverVersion do
let(:fixtures) { File.join(File.dirname(__FILE__), '..', '..', 'fixtures', 'manifests') }
describe "#version" do
subject { described_class.new(gemfile, manifest_file).version }
context "simple... |
require File.expand_path(File.dirname(__FILE__) + "/../test_helper")
class StreamTest < ActiveSupport::TestCase
setup do
@stream = Stream.make
end
context "with user" do
setup do
@user = User.make
end
%w(users favorited_streams subscribers).each do |rel|
should "have #{rel} associat... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def welcome; end
protected
def access_denied(error)
redirect_to root_path
end
end
|
load 'deploy' if respond_to?(:namespace)
set :application, 'charts'
set :repository, 'git@github.com:nazar/sound-charts-api.git'
set :scm, :git
set :deploy_via, :remote_cache
set :group, 'www-data'
set :use_sudo, false
set :keep_releases, 5
default_run_options[:pty] = true
desc "Run tasks in production environment.... |
class Step < ActiveRecord::Base
belongs_to :challenge
has_many :player_challenge_progresses
end
|
class Phrase
attr_reader :hits, :text
def initialize(params)
hits = params[:hits] || 0
text = params[:text]
raise "Phrase text cannot be empty." if text.nil?
@hits = convert_to_int(hits)
@text = clean_string(text)
end
def words
@words ||= text_to_words(text, hits)
end
private
... |
class Group < ActiveRecord::Base
attr_accessible :ownerid, :name, :user_id
belongs_to :user
has_many :group_members
has_many :videos
has_many :users, :through => :group_members
accepts_nested_attributes_for :users
end
|
class File
# Returns the contents of a file if it exists, or creates it
# and provides it to a block to write its contents.
def self.read_or_create(filename, &block) # :yields: file
File.open(filename, "w", &block) unless File.exist?(filename)
File.read(filename)
end
end
|
#!/usr/bin/env ruby
require 'redis'
if ARGV.length < 2
puts "Usage: ./insert.rb PORT N"
exit(1)
end
N = ARGV[1].to_i
PORT = ARGV[0].to_i
redis = Redis.new(:host => "localhost", :port => PORT)
start = Time.now
(1..N).each do |key|
redis.zadd("q", Random.rand(100) , key.to_s)
end
final = Time.now
elapsed = fi... |
# Get the path of the application template
path = __dir__
# Questions
api_mode = yes? 'Will we work on api mode?'
simple_command = yes? 'Will we use service objects with simple_command?'
friendly_id = yes? 'Will we use slugs with friendly id?'
change_template_language = yes? 'Will we use other template language?'
adm... |
require 'haml'
require 'hanlon/version'
require 'hanlon/methods_finder'
require 'hanlon/template_loader'
module Hanlon
def self.included base
base.extend TemplateLoader
end
def execute_hanlon engine, name, *args
@method_being_searched_for = name
@arguments_for_method = args
engine.render self
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.