text
stringlengths
10
2.61M
class SearchController < ApplicationController def index query = params[:q] @movies = Movie.where('title LIKE :query OR description LIKE :query OR year_released LIKE :query', query: "%#{query}%") end end
module Goodreads class Error < StandardError; end class ConfigurationError < Error ; end class Unauthorized < Error ; end class NotFound < Error ; end end
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe TwitterCldr::Tokenizers::TimespanTokenizer do describe "#tokens" do it "should return the correct list of tokens" do tokenizer = described_class.new(nil) tokenizer.tokenize("...
module Api::V1 class BalanceController < ApplicationController before_action :authenticate_user def update balance = Balance.find_by(id: params[:id]) balance.balance = balance_params.to_i if balance.save render status: 200, json: {message: "Update Successful"} else r...
class Expense < ActiveRecord::Base belongs_to :user has_many :categories_expenses, :dependent => :destroy has_many :categories, :through => :categories_expenses validates_presence_of :description, :amount validates_numericality_of :amount end
Rails.application.routes.draw do root to: 'pages#home' get 'about', to: 'pages#about' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html resources :offers, only: [ :index, :show ] do resources :redemptions, only: [ :create ] end resources :restaurants, on...
# frozen_string_literal: true class FlagsController < ApplicationController before_action :bucket, only: %i[flags national signals] title!('Flags') def flags @show_birmingham = true render(:flags, layout: 'application') end def national @show_birmingham = false @generic_logo = @bucket.link...
# Copyright 2019 The inspec-gcp-cis-benchmark Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
# frozen_string_literal: true module Zafira module Operations module User class RefreshToken include Concerns::Operationable def initialize(client) self.client = client end def call chain { refresh_token } chain { update_token } end ...
desc "This task is called by the Heroku scheduler add-on" task :send_confirmation_reminders => :environment do if Date.today.wednesday? puts "Sending Emails" User.where(confirmed: false).each do |user| if EmailAddress.valid?(user.email) ConfirmationCodeMailer.confirmation_reminder_email(user).de...
class ApplicationMailer < ActionMailer::Base default from: "fab-oger@live.fr" layout 'mailer' end
class AddTimeToVacationRequests < ActiveRecord::Migration[5.2] def change add_column :vacation_requests, :starts_at, :time add_column :vacation_requests, :ends_at, :time end end
# -*- mode: ruby -*- # vi: set ft=ruby : # # Before running vagrant up: # - Ensure that necessary ssh keys are added to ssh cookbook as templates # - Ensure that the below values are correct for your project # Vagrant.configure('2') do |config| config.vm.box = 'ubuntu/xenial64' config.vm.network 'forwarded_port', ...
namespace :services do services = %w[] # SETME actions = %w[stop start restart] services.each do |service| namespace service do actions.each do |action| desc "#{action} #{service}" task action do run "sudo monit #{action} #{rails_env}_#{service}" end end end ...
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # Shindo.tests("Fog::Compute[:softlayer] | KeyPair model", ["softlayer"]) do pending unless Fog.mocking? @sl_connection = Fog::Compute[:softlayer] @key_gen = Proc.new...
module Roglew module GL INT64_NV ||= 0x140E UNSIGNED_INT64_NV ||= 0x140F end end module GL_NV_vertex_attrib_integer_64bit module RenderHandle include Roglew::RenderHandleExtension functions [ [:glGetVertexAttribLi64vNV, [ :uint, :uint, :pointer ], :void], [:glGetVertexAt...
class CreateMembers < ActiveRecord::Migration def change create_table :members do |t| t.string :role, null: false t.string :name, null: false t.integer :family_id, null: false t.integer :points, default: 0 t.string :color, null: false t.string :img_url, null: false t.timestamp...
require 'rails_helper' describe Invitation do let (:invite) { FactoryGirl.create(:invitation) } it "Allows an event to have more than one invitation" do second_invite = FactoryGirl.build(:invitation, event: invite.event) expect(second_invite).to be_valid end it "Limits a user to one invitation per ev...
module MachO # @param value [Fixnum] the number being rounded # @param round [Fixnum] the number being rounded with # @return [Fixnum] the next number >= `value` such that `round` is its divisor # @see http://www.opensource.apple.com/source/cctools/cctools-870/libstuff/rnd.c def self.round(value, round) r...
# == Schema Information # # Table name: albums # # id :integer not null, primary key # title :string # description :text # user_id :integer # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_albums_on_user_id (user_i...
# Copyright 2013 Ride Connection # # 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 writi...
class Cart < ActiveRecord::Base belongs_to :billing_information has_many :bookings, dependent: :destroy belongs_to :search belongs_to :user validates :user_id, :search_id, presence: true validate :valid_state accepts_nested_attributes_for :bookings delegate :credit_card, to: :billing_informa...
class MigrateAdminAccounts < ActiveRecord::Migration def self.up admins = Account.find(:all, :conditions => 'admin = 1') admins.each{|acc| acc.authz.has_role 'admin'} end def self.down end end
require 'byebug' # merge_sort def merge_sort(arr) return arr if arr.length < 2 # DIVIDE: partition into left, right halves mid = arr.length / 2 left = arr.take(mid) right = arr.drop(mid) # CONQUER: sort partitions merge_sort(left) merge_sort(right) # COMBINE: combine sorted arrays merge(left,...
require 'spec_helper' describe SupportedSourceHelloWorld do it 'has the right version' do expect(SupportedSourceHelloWorld::VERSION).to eq('1.1.0') end it 'says hello world' do expect(SupportedSourceHelloWorld.hello_world).to eq('Hello world! If you can read this, the project was included successfully.'...
class Susanoo::PageContentsController < ApplicationController # # html にルビをふる # # see app/controllers/application_controller.rb # after_action :rubi_filter, only: %i(content) end
require 'rails_helper' RSpec.describe List, type: :model do subject { build(:list) } it { is_expected.to respond_to(:name) } it { is_expected.to respond_to(:position) } it { is_expected.to respond_to(:board_id) } it { is_expected.to be_valid } it { is_expected.to belong_to(:board) } it { is_expected....
# frozen_string_literal: true module Api module V1 class UsersController < ApplicationController include LoginHelper include ErrorMessageHelper include ResponseStatus include ErrorKeys def create @user = User.new(user_params) if @user.save @user.send_activ...
# your code goes here require "pry" def begins_with_r(arr) if arr.count{|e| e[0] == "r"} ==arr.length return true else return false end end def contain_a(arr) arr.collect do |e| if(e.include?("a")) e else nil end end.compact end def first_wa(arr) arr.each do |e| if(e.to...
module RackReverseProxy # Rule understands which urls need to be proxied class Rule # FIXME: It needs to be hidden attr_reader :options def initialize(spec, url = nil, options = {}) @has_custom_url = url.nil? @url = url @options = options @spec = build_matcher(spec) end ...
class TeamSubmittionsController < ApplicationController before_filter :set_team before_filter :find_or_initialize_submittion before_filter :verify_team_access before_filter :set_tabs before_filter :verify_contest_running layout 'control' def index @problems = @contest.problems.find_all ...
require 'spec_helper' describe OpenAssets::Provider::BitcoinCoreProvider do describe 'implicitly defined method#getbalance' do context 'use new provider.getbalance' do it 'returns provider.getbalance' do provider = OpenAssets::Provider::BitcoinCoreProvider.new({}) expect(provider).to receiv...
Rails.application.routes.draw do resources :posts devise_for :users root 'posts#index' get 'post/:id/likes', to: 'posts#likes', as: :likes end
json.goal do json.partial! 'api/v1/goals/show', goal: @goal end
require 'json' require 'csv' # data is from 2014 # http://kff.org/global-indicator/people-living-with-hivaids/# def separate_comma(number) number.to_s.chars.to_a.reverse.each_slice(3).map(&:join).join(",").reverse end csv_data = File.read('hiv_aids_data_by_country.csv') csv = CSV.parse(csv_data, :headers=> true) c...
require 'pi_piper' module SMSService # A LED handler class LEDHandler def initialize(pins) unless pins.respond_to? 'each' raise ArgumentError, 'pins must be an array' end @pins = {} pins.each do |p| pin = PiPiper::Pin.new(pin: p, direction: :out) @pins[p] = pin ...
class CreateJointTableIngredientsPets < ActiveRecord::Migration def change create_table :ingredients_pets, :id => false do |t| t.references :ingredients t.references :pets end end end
# Self pairings are disallowed. require 'json' require 'fileutils' module GenData # A directory inside this directory will be created for this data. DATA_BASE_DIR = File.join('.', 'data') DEFAULT_SEED = 4 OPTIONS = [ { :id => 'people', :short => 'p', :long => 'people', ...
class Picture < ActiveRecord::Base belongs_to :gallery validates :gallery, :presence => true Paperclip.interpolates :gallery_id do |attachment, style| attachment.instance.gallery_id end has_attached_file :photo, :styles => {:normal => "600x400#", :thumbnail => "225x150#"}, :defau...
# == Schema Information # # Table name: resources # # id :integer not null, primary key # book_id :integer # created_at :datetime not null # updated_at :datetime not null # user_id :integer # require 'spec_helper' describe Resource do let(:book) { create :book } let(:us...
class SpaceAge attr_reader :seconds def initialize(seconds) @seconds = seconds @hours_in_day = 24 @mins_in_hour = 60 @sec_in_min = 60 yearly_orbit_in_days end def seconds_to_days @seconds / @sec_in_min / @mins_in_hour / @hours_in_day end def yearly_orbit_in_days @EART...
class Region < ActiveRecord::Base has_and_belongs_to_many :seasons end
require 'test_helper' class DirectoriosControllerTest < ActionController::TestCase setup do @directorio = directorios(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:directorios) end test "should get new" do get :new assert_response :...
class AddSource < ActiveRecord::Migration def change add_column :extensions, :source, :string end end
require 'spec_helper' describe Swift::Pyrite::Transformer do subject { described_class.new({}) } describe '#unwind_type' do context "simple type" do let(:input_expression) do { :type_name=>"String" } end it "unwinds to 'String'" do str = subject.unwind_type...
require_relative './init' RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods end describe "ResetPasswordService" do def setup_logger log_instance_double = double('logger instance') allow(log_instance_double).to receive(:info) logger_double = double('logger') allow(logger_doub...
require 'rails_helper' RSpec.describe Api::CardsController, type: :controller do describe "GET #index" do it "returns the correct cards" do card_1 = create(:card) card_2 = create(:card) get :index cards_response = json_response ids = card_ids_from_response cards_response ex...
require 'rails_helper' RSpec.describe PositionsController, type: :controller do describe "#index" do it "正常にレスポンスを返す" do get :index expect(response).to be_successful end end describe "#show" do before do @acount = FactoryBot.create(:account) @area = FactoryBot.c...
require 'pg' require 'bcrypt' class User attr_reader :id, :username, :password, :signed_in attr_writer :signed_in def initialize(id:, username:, password:) @id = id @username = username @password = password @signed_in = false end def self.all if ENV['RACK_ENV'] == 'test' connection = PG....
module Task class AttributeRevisionRecord < ActiveRecord::Base self.table_name = 'task_attribute_revisions' self.record_timestamps = false attr_accessible :attribute_name, :updated_value, :update_date, :next_update_date, :sequence_number, :computed serialize :updated_value scope :computed...
require 'rails_helper' RSpec.describe Album, type: :model do describe 'validations' do it 'has a valid factory' do expect(FactoryGirl.create(:album)).to be_valid end end describe 'associations' do it { should belong_to(:member) } it { should have_many(:images) } it { should have_many(:a...
class Subscription < ActiveRecord::Base # attr_accessible :title, :body validates :project_id, :presence => true, :numericality => { :only_integer => true } validates :luser_id, :presence => true, :numericality => { :only_integer => true } belongs_to :luser belongs_to :project end
class Installations < ActiveRecord::Migration class PrinterModel < ActiveRecord::Base attr_accessible :name end class InkSystem < ActiveRecord::Base attr_accessible :name end class ConsumptionProfile < ActiveRecord::Base attr_accessible :code, :name end class PrinterFunction < ActiveRecord:...
require 'spec_helper' describe Relevant::Widget do describe "to_html" do it "renders the widgets template" do TestWidget.template "Hello <%= @options[:name] %>" TestWidget.template_format :erb widget = TestWidget.setup(:name => 'Mr. Roboto') widget.to_html.should == "Hello Mr. Roboto" ...
module LinkHelper def icon_link_to(type, body, url = nil, options = {}) link_to icon_tag(type, label: body, fixed: options.delete(:fixed), join: options.delete(:join)), url, options end end
class Link attr_accessor :key, :val, :next, :prev def initialize(key = nil, val = nil) @key = key @val = val @next = nil @prev = nil end end class LinkedList include Enumerable attr_reader :head, :tail def initialize @head = Link.new @tail = Link.new @head.next = @tail @t...
require 'json' class WishesController < ApplicationController def show @wish = Wish.friendly.find(params[:id]) end def new @list = List.friendly.find(params[:list_id]) @wish = Wish.new authorize @wish end def create @wish = Wish.new @wish.assign_attributes(wish_params) @list = L...
require 'test_helper' class ContentsControllerTest < ActionController::TestCase setup do @campaign = campaigns(:one) @content = contents(:one) end test "should get index" do get :index, params: { campaign_id: @campaign } assert_response :success end test "should get new" do get :new, pa...
class GoodDog attr_accessor :name, :height, :weight def initialize(name) @name = name end def speak "#{@name} says arf!" end def self.what_am_i puts "I'm a GoodDog class!" end def to_s "this is dog" end end sparky = GoodDog.new("Sparky") #puts sparky.speak #puts sparky.name #spark...
class CocktailHour < ActiveRecord::Base belongs_to :event has_and_belongs_to_many :instruments validates :start_time, presence: true, unless: :not_performing_at_cocktail? validates :end_time, presence: true, unless: :not_performing_at_cocktail? private def not_performing_at_cocktail? !performing en...
require 'spec_helper' CSV_EXAMPLES = YAML.load_file(Rails.root.join('spec/fixtures/usgs_service/sample_csv_fragments.yml')) describe USGSService do let(:service) { FactoryGirl.build :usgs_service } subject { service } context 'class-level interface' do subject { USGSService } describe '.latest' do ...
class Place < ActiveRecord::Base validates_presence_of :name validates_presence_of :phone validates_presence_of :address validates_presence_of :website validates_presence_of :user_id belongs_to :user geocoded_by :address after_validation :geocode end
class SearchSerializer include FastJsonapi::ObjectSerializer attributes :id, :query, :url has_many :cocktails end
def double_consonants(str) output = '' str.each_char do |char| output << char if char =~ /[a-z&&[^aeiou]]/i output << char end end output end puts double_consonants('String') == "SSttrrinngg" puts double_consonants("Hello-World!") == "HHellllo-WWorrlldd!" puts double_consonants("July 4th") ==...
namespace :db do desc "Erase and fill database" task :populate => :environment do [Location].each(&:delete_all) Dir.glob(Rails.root + 'app/IPlogs/*.log') do |file| puts file File.open(file, "r") do |f| f.each_line do |line| data = line.split(',') Location.cr...
module ProjectsHelper def add_responsibility_link(name) link_to_function name do |page| page.insert_html :bottom, :responsibilities, :partial => 'responsibility', :object => Responsibility.new end end def prefix(responsibility) "project[#{responsibility.new_record? ? 'new...
class MonitoringsStudent < ApplicationRecord belongs_to :student, class_name: 'User', foreign_key: 'student_id', validate: true belongs_to :monitoring end
class Page < ApplicationRecord belongs_to :subject has_and_belongs_to_many :users scope :sample, -> {offset(rand(Page.count)).first} end
#!/usr/bin/env ruby # # Stats the TEM's firmware version, buffers, and keys, and dumps them to stdout. # # Author:: Victor Costan # Copyright:: Copyright (C) 2007 Massachusetts Institute of Technology # License:: MIT require 'rubygems' require 'tem_ruby' require 'pp' Tem.auto_conf print "Connected to TEM using #{$te...
class KittensController < ApplicationController def index @kittens = Kitten.all respond_to do |format| format.html format.json { render :json => @kittens } end end def show @kitten = Kitten.find(params[:id]) respond_to do |format| ...
# -*- coding: utf-8 -*- =begin Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês, sabendo-se que são descontados 11% para o Imposto de Renda, 8% para o INSS e 5% para o sindicato, faça um programa que nos dê: a. salá...
class TermsController < ApplicationController def index return if params[:search].nil? headers['Last-Modified'] = Time.now.httpdate @tree = Tree.find_by_name(params[:search]) @term = Term.new render 'errors/no_such_tree' and return if @tree.nil? respond_to do |f| f.html f.jso...
module AdobeConnect # Public: Current Gem version. VERSION = '1.0.8' end
#!/usr/bin/env ruby # Quick and simple script to transform user input # into ascii equivalent values. # Not including spaces. # ASCII character mapping def mapping(stringToSplit) arrSplit = stringToSplit.scan /\w/ return arrSplit.map { |n| n.ord } end if __FILE__ == $0 print "Enter the string that is to ...
require 'test/unit' require_relative 'show' class ClassesTest < Test::Unit::TestCase def setup @show = Show.new end def test_1 @show.regex('price 12 dollari', /[aeiou]/) # il primo match @show.regex('price 12 dollari', /[\s]/) # questi li prende @show.regex('price 12$ dollaroni', /[$]/) #quelli ...
# This class is used to experiment with classes and functions in Ruby. class Bowling attr_reader :score def initialize @score = 0 end def hit(pin_count) @score += pin_count end end
class Customer < ApplicationRecord include Pinable include Reviewable include Tokenizable include Hashable # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberabl...
require 'rails_helper' RSpec.describe 'Registration', js: true do let!(:gym) { create(:gym) } before do visit new_user_registration_path end it 'successfully registers' do fill_in 'First Name', with: 'Test' fill_in 'Last Name', with: 'User' fill_in 'Email', with: 'test.user@email.com' fi...
class ArticulosController < ApplicationController def index @articulos = Articulo.all end def show @articulo = Articulo.find(params[:id]) end def new end def create @articulo = Articulo.new(articulo_params) @articulo.save redirect_to @articulo end private def articulo_params params.requi...
#!/usr/bin/env ruby # (c) Copyright 2016 Thoughtgang <http://www.thoughtgang.org> # Utility for finding filenames in a Plan R repo require 'plan-r/application/cli' require 'plan-r/repo' class App < PlanR::CliApplication def self.disable_plugins?; true; end def self.disable_jruby?; true; end def self.disable_vc...
class Comment include Mongoid::Document field :author, type: String field :comment, type: String # each comment is embeded in a post embedded_in :post end
class Type < ActiveRecord::Base validates :name, presence: true has_many :games, dependent: :destroy end
class SubscriptionsController < ApplicationController layout :orders_layout include UserInformation before_action :authenticate_user!, except: [:new, :create] before_action :check_admin, except: [:new, :create] before_action :verify_actions_for_filter, only: :filter before_action :load_subscription, only: ...
module Issues class UpdateComment prepend SimpleCommand attr_reader :current_user, :args, :id, :comment_id, :message def initialize(current_user, args) @id = args[:id] @comment_id = args[:comment_id] @message = args[:messag...
platform 'osx-13-arm64' do |plat| plat.inherit_from_default plat.output_dir File.join('apple', '13', 'puppet7', 'arm64') end
Before do @old_root_node_seed = Constants::ROOT_SERIALIZED_ADDRESS silence_warnings do Constants::ROOT_SERIALIZED_ADDRESS = MoneyTree::Master.new(seed_hex: '0123456789abcdef').to_serialized_address end end After do silence_warnings do Constants::ROOT_SERIALIZED_ADDRESS = @old_root_node_seed end end
require 'rails_helper' RSpec.describe Vote, type: :model do it { should validate_presence_of(:comic_id) } it { should validate_uniqueness_of(:comic_id) } end
module Cms::MealTypesHelper def set_selected(meal_type, i, key, time_type) time_slot_field_name = "#{get_slot_number_string(i).downcase}_slot" time_for_time_slot = meal_type.send(time_slot_field_name) if !time_for_time_slot.blank? time_for_time_slot_split = time_for_time_slot.split("-") retu...
namespace :xylophone do desc 'bootstrap the xylophone application from a new image' task :bootstrap do system('bundle install') system('bundle exec rake db:migrate') system('bundle exec rake db:seed') system('bundle exec rake db:migrate RAILS_ENV=test') system('bundle exec rake db:seed RAILS_EN...
module SequelSpec module Matchers module Validation class ValidateSchemaTypesMatcher < ValidateMatcher def description desc = "validate schema types of #{@attribute.inspect}" desc << " with option(s) #{hash_to_nice_string @options}" unless @options.empty? desc e...
class Person < ActiveRecord::Base using_access_control belongs_to :user has_friendly_id :name, :use_slug => true validates_presence_of :name, :job_title, :email, :phone, :mobile, :profile, :user validates_uniqueness_of :name, :email validates_format_of :email, :with => %r{\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a...
require 'rails_helper' RSpec.describe User, type: :model do it { should have_many(:projects) } it { should have_many(:tasks).through(:projects) } end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe TextfilesController do def mock_textfile(stubs={}) @mock_textfile ||= mock_model(Textfile, stubs) @mock_textfile.stub!(:needs_fs_update=) @mock_textfile.stub!(:modified_at=) return @mock_textfile end describe "GET ind...
# frozen_string_literal: true feature 'Authentication user', js: true do before(:all) do @file = './spec/test_data/credentials.yaml' @user = User.new @user.save_to_file(@file) end before(:each) do @home_page = HomePage.new @home_page.load end after(:all) { File.delete(@file) } scenar...
require 'peep' require 'pg' require_relative '../helper_methods.rb' describe Peep do let(:con) { PG.connect test_database } let(:test_database) { { dbname: 'chitter_chatter_test' }} describe '.create' do it 'creates a new peep' do peep = Peep.create(message: "Henlo World") expect(peep).to be_a ...
class User < ActiveRecord::Base validates_uniqueness_of :email, presence: true has_secure_password has_and_belongs_to_many :gifs ############FAVES########## def favorite(url) unless self.gifs.include?(url) self.gifs << url end end def unfavorite(url) self.gifs.delete(Gif.where(url: url))...
class FontArchitypeRenner < Formula version "001.000" url "https://fontlot.com/wp-content/uploads/2017/08/archityperenner.zip" desc "Architype Renner" homepage "https://fontlot.com/4598/architype-renner/" def install (share/"fonts").install "ArchitypeRenner-Bold.otf" (share/"fonts").install "Architype...
# Code your prompts here! # Try starting out with puts'ing a string. puts "Hi, you've been invited to a party! What is your name?" guest_name = gets.chomp.capitalize puts "What is the party?" party_name = gets.chomp puts "When is it?" date = gets.chomp puts "What time is it?" time = gets.chomp puts "Who is the h...
require 'rubygems' require 'neography' require 'sinatra/base' require 'uri' class Neovigator < Sinatra::Application set :haml, :format => :html5 set :app_file, __FILE__ configure :test do require 'net-http-spy' Net::HTTP.http_logger_options = {:verbose => true} end helpers do def link_to(url,...
require 'rails_helper' RSpec.describe UsersController, type: :controller do let(:stripe_helper) { StripeMock.create_test_helper } before { StripeMock.start } after { StripeMock.stop } it "updates the users payment method" do @request.env["devise.mapping"] = Devise.mappings[:user] plan = stripe_helper....