text stringlengths 10 2.61M |
|---|
# frozen_string_literal: true
# We want to ensure that we always have an up to date copy
# of all the Stripe plans locally saved in the database.
class StripePlanFetcher
def self.store_locally
Stripe::Plan.all.each do |plan|
local_plan = Plan.find_by(stripe_id: plan.id)
if !local_plan.nil?
up... |
class AddFieldsToCheckout < ActiveRecord::Migration[5.2]
def change
add_column :checkouts, :basket_total, :integer
add_column :checkouts, :basket_discount, :integer
add_column :checkouts, :amount_payable, :integer
end
end
|
class UserPassController < ApplicationController
include SetUser
include UserConfirmation
include UserSignedIn
before_action :user_signed_in
before_action :set_user
before_action :user_confirmation
#パスワード/メールアドレスの編集機能
def update
if @user.update(user_password_params)
sign_in(@user, bypass:... |
# Pre-Exercise Note
# From this point on, we will be using the command line and pry to test our code, navigate our computer, and perform many other amazing tasks.
# This means that we are not using repl.it anymore to test our code.
# Getting comfortable with these tools early will be very important in becoming an eff... |
Pod::Spec.new do |s|
s.name = 'BitFiddle'
s.version = '0.2.0'
s.summary = 'A tiny library for reading and interpreting raw data.'
s.description = <<-DESC
BitFiddle is a library for reading and interpreting raw data. It makes use of the type system to create safe interfaces for convertin... |
require "rails_helper"
feature "Author page" do
let(:author) { create :user }
let!(:article) { create :article, user: author }
scenario "Someone visits author's page" do
visit author_path(author)
expect(page).to have_content(author.full_name)
expect(page).to have_content(article.title)
expect(p... |
class MomentumCms::File < ActiveRecord::Base
# == MomentumCms ==========================================================
include MomentumCms::BelongsToSite
self.table_name = 'momentum_cms_files'
# == Constants ============================================================
attr_accessor :delete_file
# == ... |
module QBIntegration
module Service
class SalesReceipt < Base
attr_reader :order, :payload
attr_reader :payment_method_service, :line_service, :account_service, :customer_service
def initialize(config, payload, options = { dependencies: true })
super("SalesReceipt", config)
@or... |
require 'test_helper'
class InventoriesControllerTest < ActionDispatch::IntegrationTest
setup do
@inventory = inventories(:one)
end
test "should get index" do
get inventories_url
assert_response :success
end
test "should get new" do
get new_inventory_url
assert_response :success
end
... |
module UsersHelper
def display_avatar user, size = Settings.user.gravatar_size
if user.avatar_user.url
image_tag(user.avatar_user.to_s, size: "#{size}x#{size}", class: "avatar")
else
image_tag("avatar-default.png", size: "#{size}x#{size}", class: "avatar")
end
end
end
|
class BooksController < ApplicationController
def index
@books = Book.where('purchased = false')
@books = @books.search(params[:search]) if params[:search].present?
if params[:condition_id].present?
@books = @books.condition_id(params[:condition_id])
end
end
def show
if user_signed_in? && c... |
require 'logger'
# General utility functions
module Util
LOG = Logger.new(STDOUT)
# creates grammatical list from list-like object
# see accompanying rspec tests for examples
def listify(list)
return nil if list.nil?
begin
list = list.to_a
rescue NoMethodError
LOG.warn("can't make an ... |
class Subscription < ActiveRecord::Base
belongs_to :plan
belongs_to :user
before_create do |subscription|
return subscription.plan.seats_open?
end
end |
module Error
class WebError < StandardError
attr_reader :status, :error, :message
def initialize(message, error, status)
@message = message
@error = error
@status = status
end
end
end
|
class TicketsDatatable < ApplicationDatatable
delegate :edit_ticket_path, to: :@view
private
def data
tickets.map do |ticket|
[].tap do |column|
column << ticket.correlative
column << ticket.memo
column << ticket.ticket_number
column << ticket.project_name
colum... |
class CreateAddresses < ActiveRecord::Migration[5.0]
def change
create_table :addresses do |t|
# 基本信息
t.string :country
t.string :state
t.string :city
t.string :post_code
t.string :address_line1
t.string :address_line2
# 联系方式
t.string :phone
t.str... |
module OpenAgent
module Message
module SIF_Request
class SIF_Condition
include ROXML
xml_name 'SIF_Condition'
xml_accessor :sif_element, :from => 'SIF_Element'
xml_accessor :sif_operator, :from => 'SIF_Operator'
xml_accessor :sif_value, :from => 'SIF_... |
Wedding::Application.routes.draw do
get 'login' => 'sessions#new'
get 'logout' => 'sessions#destroy'
resources :sessions, only: :create
root to: 'home#index'
post '/rsvp' => 'rsvp#create'
namespace :admin do
resource :users, only: [:edit, :update]
resources :images, except: [:edit, :show]
ro... |
require 'spec_helper'
require 'erb'
include ERB::Util
describe Api::V1::CompanyController do
describe "PATCH route" do
let(:params) { @attrs.to_json }
before :all do
# create access token
@token = ApiKey.create!.access_token
@attrs = FactoryGirl.attributes_for(:company)
# Add t... |
feature 'Navigation bar' do
scenario 'shown only for for signed users' do
sign_in_as_admin
visit root_path
expect(page).to have_link t('application.navigation.sign_out')
end
scenario 'hidden from guests' do
visit root_path
expect(page).to have_no_link t('application.navigation.sign_out')
en... |
#!/usr/bin/env ruby
def main()
errorLimit = get_input()
approxe = calculateE(errorLimit)
puts "Approximate value of e: #{approxe}"
end
def factorial(num)
if num < 0
return -1
end
factorial = 1;
if num == 0
return factorial
end
counter = 1
while counter <= num
factorial *= counter
counter += 1
end... |
require 'net/http'
require 'net/https'
require 'cgi'
require 'mail'
module Jangomail
class Mailer
def initialize(values = {})
self.settings = { :api_url => 'http://api.jangomail.com/api.asmx/SendTransactionalEmail',
:options => {},
... |
require 'json'
require 'net/http'
require 'map'
load '../src/API/units.rb'
module Weather
class << self
ROOT = "http://query.yahooapis.com/v1/public/yql"
def lookup(woeid, unit = Units::CELSIUS)
acceptable_units = [Units::CELSIUS, Units::FAHRENHEIT]
unit = Units::CELSIUS unless acceptable_unit... |
##
# Environment setup
require 'sinatra'
require 'pp'
require 'erb'
require 'yaml'
require 'dalli'
require 'oauth'
require 'logger'
require 'multi_json'
require 'mongo_mapper'
require 'google/api_client'
require 'rack/session/dalli'
ENV['RACK_ENV'] ||= 'development'
FS_APPLICATION_ROOT = File::dirname(File::expand_pat... |
Gem::Specification.new do |s|
s.name = 'ses-proxy'
s.version = '0.3.3'
s.date = '2012-12-21'
s.summary = "SMTP Proxy for Amazon Simple Email Service with bounce and complaints support"
s.authors = ["Massimo Maino"]
s.email = 'maintux@gmail.com'
s.executables = ['ses_proxy']... |
require 'colorize'
require 'synchronisable/error_handler'
require 'synchronisable/context'
require 'synchronisable/input/parser'
require 'synchronisable/source'
require 'synchronisable/models/import'
require 'synchronisable/helper/logging'
require 'synchronisable/worker/record'
require 'synchronisable/worker/associati... |
class UsersController < ApplicationController
before_filter :get_logged_in_user, :only => [:show, :edit, :update]
def new
@user = User.new
end
def create
user_params = params.require(:user).permit(:username, :password, :real_name, :password_confirmation, :picture)
@user = User.new user_params
... |
require 'grit'
require 'fileutils'
require 'git_spelunk/blame'
module GitSpelunk
class FileContext
attr_accessor :line_number
attr_reader :repo, :sha, :file
def initialize(file, options = {})
@sha = options[:sha] || 'HEAD'
@line_number = options[:line_number] || 1
@repo = options.fetc... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe SingleValuedForm do
subject(:etd) { TestForm.new(work, nil, nil) }
let(:work) { FactoryBot.build :etd }
before do
class TestForm < Hyrax::Forms::WorkForm
include SingleValuedForm
end
TestForm.single_valued_fields = [:degree]
... |
# == Schema Information
#
# Table name: datos_importados
#
# id :integer not null, primary key
# artista :string(255)
# fecha :date
# horario :time
# lugar :string(255)
# direccion1 :string(255)
# barrio1 :string(255)
# web1 :string(255)
# mail1 ... |
class ChangeDataTypeForTableColumn < ActiveRecord::Migration
def up
change_column :authors, :description, :text
end
end
|
# 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... |
require 'rails_helper'
RSpec.describe 'routes for thermostat app', type: :routing do
describe 'Reading' do
it 'routes to /readings' do
expect(post: '/readings')
.to route_to(controller: 'readings', action: 'create')
end
it 'routes to /readings/{id}' do
expect(
get: '/readings... |
class TranslateImageProjectCaptions < ActiveRecord::Migration
def up
add_column Refinery::ImageProject.table_name, :id, :primary_key
Refinery::ImageProject.reset_column_information
unless defined?(Refinery::ImageProject::Translation) && Refinery::ImageProject::Translation.table_exists?
Refinery::Im... |
# 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 UsersController < ApplicationController
before_action :authenticate_user!, only: [:edit, :update, :destroy, :manage, :import]
# before_action :correct_user, only: [:edit, :update, :manage, :import]
before_action :admin_user, only: :destroy
def index
@users = User.all
#@users = User.paginate(pag... |
module Cultivation
class PackageAdjustReason
include Mongoid::Document
include Mongoid::Timestamps::Short
field :name, type: String
field :requires_note, type: Boolean, default: -> { false }
end
end
|
require 'spec_helper'
describe "Output from `rake -T`" do
def rake_t_output
`cd spec/rails_app && rake -T`
end
it "should include the default requirejs task" do
rake_t_output.should =~ /requirejs\s/
end
it "should include the clean task" do
rake_t_output.should =~ /requirejs:clean\s/
end
en... |
require "test_helper"
describe Household do
let(:household) { Household.new }
should have_many(:people).dependent(:destroy)
should have_many(:vehicles).through(:people)
should validate_presence_of(:address);
should validate_presence_of(:zip);
should validate_presence_of(:city);
should validate_presence_... |
require 'prime'
def common_prime_divisors(a, b)
common_prime_divisors = 0
for i in 0...a.length
maxValue = [a[i],b[i]].max
minValue = [a[i],b[i]].min
next if skip?(minValue, maxValue)
common_prime_divisors += counting(minValue, maxValue)
end
common_prime_divisors
end
def prime?(number)
P... |
# frozen_string_literal: true
class SearchController < ApplicationController
before_action :authenticate_as_privileged!
def search # rubocop:disable Metrics/AbcSize
render_as_json do
matches = params[:keyword].match(/(\s*branch:\s*(\w+))/i)
guide_only = params[:keyword].match(/(is:\s*guide)/i)
... |
class FontNunito < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/nunito"
desc "Nunito"
homepage "https://fonts.google.com/specimen/Nunito"
def install
(share/"fonts").install "Nunito-Italic[wght].ttf"
(share/"fonts").install "Nun... |
# frozen_string_literal: true
module SeeYouCup
class Waypoint
STYLE_MAP = {
0 => 'Unknown',
1 => 'Waypoint',
2 => 'Airfield with grass surface runway',
3 => 'Outlanding',
4 => 'Gliding airfield',
5 => 'Airfield with solid surface runway',
6 => 'Mountain Pass',
7 =>... |
require 'mkmf'
dir_config("at_fork")
unless have_header('pthread.h') && have_func('pthread_atfork')
raise 'This extension requires posix threads to be available and capable of atfork'
end
create_makefile("at_fork")
|
# frozen_string_literal: true
#
# Fluentd Kubernetes Metadata Filter Plugin - Enrich Fluentd events with
# Kubernetes metadata
#
# Copyright 2017 Red Hat, 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 ... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Room, type: :model do
describe 'associations' do
it { is_expected.to have_many(:bookings).dependent(:destroy) }
end
describe 'validations' do
it { is_expected.to validate_presence_of(:name) }
it { is_expected.to validate_length_of(... |
Rails.application.routes.draw do
devise_for :admins
get 'persons/profile'
resources :categories
resources :projects
resources :photos
resources :posts
resources :home, only: :index do
collection do
get :about
end
end
root to: 'home#index'
end
|
# frozen_string_literal: true
require_relative 'model'
# Job represents BambooHR job, can export itself to csv
class Job < Model
def initialize(hash)
read_from_hash!(hash)
lead = hash['hiringLead']
self.hiringLead = lead['firstName'] + ' ' + lead['lastName']
end
def to_s
"<Job##{id} #{title}>"
... |
# frozen_string_literal: true
require 'printer'
RSpec.describe Printer do
subject { described_class.new(filtered_logs) }
let(:filtered_logs) do
{ most_page_views: { '/about/2' => 90, '/contact' => 89, '/index' => 82 },
most_unique_page_views: { '/help_page/1' => 23, '/contact' => 23, '/home' => 23 } }
... |
class PeopleOrganizationsController < ApplicationController
before_action :set_people_organization, only: [:show, :edit, :update, :destroy]
# GET /people_organizations
# GET /people_organizations.json
def index
@people_organizations = PeopleOrganization.search(params[:search]).order("OrganizationName")
e... |
#
# Implementation of bit-operations
#
module RPL
class Words
def Words.register_bit_dict rpl
rpl.instance_exec do
# get/set wordsize
defop("rcws", []) { self.wordsize }
defop("stws", [Integer]) { |ws| self.wordsize = ws ; nil }
defop("and", [Integer, Integer]) { |a... |
class AppointmentDatatable < AjaxDatatablesRails::Base
def_delegators :@view, :link_to, :edit_admin_appointment_path, :admin_appointment_path
def view_columns
# Declare strings in this format: ModelName.column_name
# or in aliased_join_table.column_name format
@view_columns ||= {
date: { source:... |
require 'fileutils'
class SetupCreator
attr_accessor :config
attr_accessor :builder
attr_accessor :configurator
attr_accessor :temp_path
# Creates individual temporary path for this particular setup
def create_temp_path
if(!File.directory?(config['temp_path']))
Dir.mkdir(config['temp_path'])
... |
class Api::BoatsController < ApplicationController
def index
boats = Boat.all
render json: boats, status: 200
end
def create
boat = Boat.new(boat_params)
if boat.save
render json: boat, status: 201
else
render json: boat.errors, status: :unprocessable_entity
end
end
pri... |
class Cup < ActiveRecord::Base
extend FriendlyId
friendly_id :name, use: :slugged
delegate :update_results, to: :standing
has_many :stages
has_many :matches, through: :stages
has_many :groups
has_many :teams, through: :groups
has_one :standing, as: :rateable,
readonly: true
has_... |
module Asaas
class Fine < Model
FineTypes = Types::Strict::String.enum('FIXED', 'PERCENTAGE')
attribute :value, Types::Coercible::Float
attribute :type, FineTypes.optional.default(nil)
end
end |
class Users::SessionsController < Devise::SessionsController
def new_guest
user = User.guest
sign_in user
flash[:success] = 'ゲストユーザーとしてログインしました。'
redirect_to user_path(user)
end
def reject_user
@user = User.find_by(email: params[:user][:email].downcase)
if @user
if @user.valid_passw... |
class AddDescriptionLogoSummaryToAgeTags < ActiveRecord::Migration
def self.up
add_column :age_tags, :description, :text
add_column :age_tags, :summary, :string
add_column :age_tags, :logo, :string
add_column :age_tags, :is_index_hot, :boolean, :default => false
end
def self.down
remove_colum... |
# require 'troles/common/marshaller/generic'
module Troles::Common
module Marshaller
class Bitmask < Generic
attr_reader :role_subject, :valid_roles
def initialize role_subject
super
end
def read
valid_roles.reject do |r|
num = as_number(ds_field_value)
... |
require 'rails_helper'
describe Item do
let(:item) { FactoryGirl.create(:item, department_id: Department.first) }
before do
Store.all.each do |store|
FactoryGirl.create(:product, item_id: item.id, store_id: store.id)
end
end
subject { item }
it { should respond_to :department }
it { shoul... |
module RPS
class Session
attr_reader :id, :user_id
@@counter = 0
def initialize(uid)
@@counter += 1
@id = @@counter
@user_id = uid
end
end
end |
require 'rails_helper'
RSpec.describe StoreThermostatReading, type: :interactor do
subject(:result) do
StoreThermostatReading.call(
params: reading_params, thermostat: thermostat
)
end
describe '.call' do
before do
allow(thermostat).to receive(:next_sequence_number).and_return(1)
a... |
# Read about factories at http://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :assets, :class => AccountType do
name "Assets"
code "assets"
note "Asset Desc"
end
end
|
class ChangeColumnInComments < ActiveRecord::Migration
def change
rename_column :comments, :concert_id, :music_concert_id
end
end
|
class Tag < ApplicationRecord
has_many :tag_tickets
has_many :tickets, through: :tag_tickets
end
|
FactoryBot.define do
factory :dog do
title { '綺麗な毛色の可愛い子です!' }
dog_gender {1}
dog_age_id {2}
vaccine {2}
surgery {2}
prefecture_id {2}
feature { '普段は大人しいですが、散歩に行く時はすごく喜びます!' }
reason { '行政処分センターより保護しました。' }
remarks { 'ご家族全員が賛成して迎えてくださる方'... |
class Travelport::Request::LowFareSearchReq < Travelport::Request::Base
attr_accessor :sectors
attr_accessor :adults
attr_accessor :infants
attr_accessor :children
attr_accessor :cabin
attr_accessor :provider_code
attr_accessor :flexible_dates
default_for :provider_code, '1G'
default_for :xmlns, 'ht... |
class AddColumnPersonIdToEmploymentStatuses < ActiveRecord::Migration
def change
add_column :employment_statuses, :company_id, :integer
add_column :employment_statuses, :person_id, :integer
end
end
|
require 'parser/current'
module Solargraph
class CodeMap
# The root node of the parsed code.
#
# @return [AST::Node]
attr_accessor :node
# The source code being analyzed.
#
# @return [String]
attr_reader :code
# The source code after modification to fix syntax er... |
class FontAnonymousPro < Formula
version "1.002"
sha256 "6d165fd08fe2827f38656c26f644eb1f5d6a0f1cb067cb758c7f295a333eb112"
url "https://www.marksimonson.com/assets/content/fonts/AnonymousPro-#{version.to_s.gsub(".", "_")}.zip"
desc "Anonymous Pro"
homepage "https://www.marksimonson.com/fonts/view/anonymous-pr... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe HomeController, type: :controller do
before do
@user = FactoryGirl.create(:user)
get :index
end
it 'Returns a 200 status OK' do
expect(response).to be_success
end
it 'allows authenticated access' do
current_user = sign_in @u... |
#
# Copyright 2014 Stormpath, 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 to in wri... |
require 'nokogiri'
require 'open-uri'
require 'pry'
class Rosecollector::Roses
attr_accessor :name, :price, :url, :description
def self.scrape_site
doc = Nokogiri::HTML(open("https://www.edmundsroses.com/category/8"))
@roses = []
doc.css("section.product").each do |r|
rose ... |
json.set! @city.id do
json.id @city.id
json.name @city.name
json.image_url @city.image_url
json.events do
@city.events.each do |event|
json.set! event.id do
json.id event.id
json.date event.date
json.time event.time
json.address event.address
json.description ev... |
module Vanity
VERSION = "4.0.4"
module Version
version = VERSION.to_s.split(".").map { |i| i.to_i }
MAJOR = version[0]
MINOR = version[1]
PATCH = version[2]
STRING = "#{MAJOR}.#{MINOR}.#{PATCH}"
end
end
|
require_relative 'color_sequence'
require_relative 'display'
require_relative 'guess_checker'
require_relative 'input'
require 'pry'
class GameManager
attr_reader :input, :display, :stream
def initialize(interface, stdin)
@display = Display.new
@input = Input.new
@guess_checker = GuessChecker.new
... |
class CreateShopProducts < ActiveRecord::Migration
def self.up
create_table :shop_products, :force => true do |t|
t.string :name,:limit=>100
t.string :url,:limit=>200
t.string :content,:limit=>300
t.float :price
t.float :money_back
t.float :discount
t.integer :shop_id
... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Roster::PastCommander do
let(:user) { create(:user, first_name: 'Jack', last_name: 'Frost') }
describe 'validation' do
context 'with a user' do
it 'is valid without a name' do
pc = build(:roster_past_commander, name: nil, user:... |
module API
module V1
class StudentDeliveriesGeneratePresentations < API::V1::Base
before do
authenticate_user
end
namespace :student_deliveries do
route_param :id do
desc 'Get Student delivery Presentation'
get :presentation do
delivery = Student... |
class Computer < ApplicationRecord
has_many :memories
has_one :cpu
validates :name, presence: true
end
|
class AddNextRepetiotionAtToWords < ActiveRecord::Migration[5.0]
def change
add_column :words, :next_repetition_at, :datetime
end
end
|
require 'net/scp'
module Backup
module Storage
class SCP < Base
attr_accessor :user, :password, :ip, :path, :tmp_path, :final_file
# Stores the backup file on the remote server using SCP
def initialize(adapter)
%w(ip user password path).each do |method|
send("#{m... |
#1
def sum_of_sums(arr)
counter = 0
sum = 0
arr.each.inject(:+) do |num|
multiplier = arr.size - counter
sum += arr[counter] * multiplier
counter += 1
sum
end
end
sum_of_sums([3, 5, 2]) == (3) + (3 + 5) + (3 + 5 + 2) # -> (21)
sum_of_sums([1, 5, 7, 3]) == (1) + (1 + 5) + (1 + 5 + 7) + (1 + 5... |
class Owner
include Draper::Decoratable
attr_accessor *Settings.person.to_hash.keys
def initialize
Settings.person.each do |key, value|
self.send("#{key}=", value)
end
end
end |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe Mixpanel::Client do
before :all do
@client = Mixpanel::Client.new(:api_key => 'test_key', :api_secret => 'test_secret')
@uri = Regexp.escape(Mixpanel::Client::BASE_URI)
end
context 'when initializing a new Mixpanel::Client' do... |
# == Schema Information
#
# Table name: album_photos
#
# id :integer not null, primary key
# album_id :integer not null
# photo_id :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class AlbumPhoto < ApplicationRecord
valid... |
#!/usr/local/bin/ruby
# encoding: utf-8
# author: Matthew Dromazos
require 'csv'
require 'word_wrap'
require 'json'
class CsvParser
def initialize(csv_file)
@csv_file = csv_file
@controls = []
read_csv
puts "\nProcessed #{@controls.count} controls"
end
def read_csv
nist_version = ''
ci... |
require "tmpdir"
require "fileutils"
require "erubis"
module EZModel
module Generator
def self.CreateModels(path, tables, overwrite=false)
return unless tables.is_a? Array
FileUtils.mkdir_p(path) if !Dir.exists?(path)
tables.each do |table_name|
_file_path = File.join(path, "#{table_n... |
module SpecRunner
class PresentedTime
def initialize(clock = ->{ Time.now })
@clock = clock
end
def call
@clock.call.strftime("%l:%M:%S %p").strip
end
end
end
|
# frozen_string_literal: true
require 'test_helper'
class StylesParserTest < Test::Unit::TestCase
context "An attachment with :convert_options" do
setup do
options = {
styles: {
thumb: "100x100",
large: "400x400"
},
convert_options: {
all: "-do_stuff",... |
module Api
module V1
class DifficultiesController < Api::V1::ApplicationBaseController
before_action :set_difficulty, only: [:show, :update, :destroy]
# GET /difficulties
def index
@difficulties = Difficulty.all
render json: @difficulties
end
# GET /difficulties/1
... |
class PhotosController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
load_and_authorize_resource :profile
load_and_authorize_resource :album, through: :profile
load_and_authorize_resource through: :album
def new
@photo = Photo.new(photo_params)
end
def create
... |
module MongoidActivityTracker
module Helpers
module ActivityHelper
def user_activity_feed(user, options = {})
options[:user] = user
activity_feed(options)
end
# Available options:
# limit - number of results to return
# user_id - limit to user id scope
# scope ... |
require 'date'
require 'rubygems'
require 'builder'
require 'svntl'
include SvnTimeline
class SubversionRepositoryMock < SubversionRepository
attr_accessor :url, :revisions, :project_name
def initialize
@revisions = ListOfRevisions.new
@initial_date = Date.today
end
def revisions_append_with_loc loc... |
require 'spec_helper'
require 'pogoplug/http_helper'
describe PogoPlug::HttpHelper do
let(:user_agent){ 'MyCompany/Faraday v0.9.0' }
before { PogoPlug::HttpHelper::DEFAULT_REQUEST_HEADERS['User-Agent'] = user_agent }
it "includes a default user agent" do
expect(PogoPlug::HttpHelper::DEFAULT_REQUEST_HEAD... |
# encoding: UTF-8
module FreeImage
##
# FreeImage supports the following image types:
#
# :unknown:: Unknown format (returned value only, never use it as input value)
# :bitmap:: Standard image: 1-, 4-, 8-, 16-, 24-, 32-bit
# :uint16:: Array of unsigned short: unsigned 16-bit
# :int16:: Array o... |
class CalculateDepreciation
def initialize(params)
@purchase_price = params[:purchase_price]
@salvage_value = params[:salvage_value] || 0
@useful_life = params[:useful_life]
@purchase_date = params[:purchase_date]
end
def calculate
calculate_monthly_depreciation
get_depreciation_schedule... |
module UserJsonSerializer
DEFAULT_JSON = {
:success => 1,
:resultCode => 200,
:user => '',
:message => ''
}
def self.build_user(user)
{ :auth_token => user.authentication_token,
:id => user.id,
:email => user.email,
:username => user.username,
:slug => user.sl... |
# Chess piece model
class ChessPiece < ActiveRecord::Base
BOARD_START_INDEX = 1
BOARD_END_INDEX = 8
belongs_to :player, class_name: 'User'
belongs_to :game
validates :type, :position_x, :position_y, :color, presence: true
enum color: [:black, :white]
scope :with_color, ->(color) { where(color: colors[... |
# Letter Swap
# Given a string of words separated by spaces, write a method that takes this string of words and returns a string in which the first and last letters of every word are swapped.
# You may assume that every word contains at least one letter, and that the string will always contain at least one word. You ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.