text
stringlengths
10
2.61M
prawn_document() do |pdf| pdf.text "Application Ruby on Rails", :size => 30, :style => :bold, :align => :center pdf.move_down 20 pdf.text "Liste des membres", :size => 22, :style => :bold pdf.move_down 10 data = [[ "Nom", "Date de naissance", "Taille", "Poids", "Fume", "Veut arrêter" ...
json.array!(@trips) do |trip| json.extract! trip, :id, :vehicle_id, :trip_date, :origin, :destination, :estimated_distance, :estimated_time_of_departure, :estimated_time_of_arrival, :estimated_start_soc, :estimated_end_soc, :hvac_status json.url trip_url(trip, format: :json) end
# frozen_string_literal: true module Api class UsersController < Api::BaseController before_action :authenticate_notself, only: [:update] before_action :authenticate_admin!, except: %i[index show update incoming_birthdays] before_action :authenticate_admin_or_manager!, only: %i[index incoming_birthdays] ...
class PullRequestsController < ApplicationController before_filter :authenticate_user! def index # We should list the pull requests either both Github and our model # We need to get the list of repos that the user has, and also get the user's github nickname # need to sync the data with the github id...
# == Schema Information # # Table name: levels # # id :integer not null, primary key # directions :text # number :integer # created_at :datetime not null # updated_at :datetime not null # class Level < ApplicationRecord has_many :answers def valid_answer?(query) answe...
require 'spec_helper' describe LineItemsHelper do context "total_items_sold" do it "should return nil when no line items are present" do helper.total_items_sold(nil).should be_nil end it "should calculate total items sold" do line_items = Array.new line_items.push(LineItem.new(:purcha...
class RegistrationsController < Devise::RegistrationsController layout "application", only:[:edit, :update] private def sign_up_params params.require(resource_name).permit(:email, :password, :password_confirmation, :current_password, :terms, :profile_attributes => [:first_name, :birth_date ]) end end
class Dashboard::Diabetes::BsBelow200GraphComponent < ApplicationComponent attr_reader :data attr_reader :region attr_reader :period attr_reader :with_ltfu def initialize(data:, region:, period:, with_ltfu: false) @data = data @region = region @period = period @with_ltfu = with_ltfu end ...
Rails.application.routes.draw do namespace :api, :defaults => {:format => :json} do namespace :v1 do resources :workouts get "/workouts", to: "workouts#index" end end end
class DockingStation DEFAULT_CAPACITY = 20 def initialize(options = {}) @capacity = options.fetch(:capacity, DEFAULT_CAPACITY) @bikes = [] end def bike_count @bikes.count end def dock bike raise "Station is full" if full? @bikes << bike end def release bike raise "Station is empty" if empty? ...
namespace :alerts do desc 'check for new activity and send emails' task check: :environment do stats = { sent: 0, users: 0 } User.find_in_batches.with_index do |users, batch| User.transaction do users.each do |user| checker = AlertChecker.new(user: user) alerts_sent = chec...
class AddProjectsToUser < ActiveRecord::Migration def change add_column :users, :projects, :text end end
require 'rails_helper' describe 'creating helper' do it 'returns a valid helper' do user1 = create(:user) user2 = create(:user2) b1 = Board.new(4) b2 = Board.new(4) attributes = { player_1: user1, player_2: user2, player_1_board: b1, player_2_board: b2, player_1_turn...
namespace :deploy do def with_tempfile_on_remote_server(&block) tempfile_name = capture('mktemp -t preparedb.XXXXXXXX').strip yield tempfile_name ensure run "rm #{tempfile_name}" end def db_connection fetch(:db_connection, {}) end def dbinfo @dbinfo ||= db_defaults.merge(db_connection...
# encoding: utf-8 # # For more information about Backup's components, see the documentation at: # http://backup.github.io/backup # require 'dotenv' require 'mkmf' require 'paint' require 'shellwords' require 'which_works' Dotenv.load! %i(GPG_KEY AWS_REGION AWS_BUCKET AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY).each do ...
require 'test_helper' class CategoryTest < ActiveSupport::TestCase # Replace this with your real tests. def setup @category = Category.new @sample_title = "Fun With Napkins!" end test "empty? returns true when categories have problem_types" do assert @category.empty? end test "empty? retu...
class Zendesk2::Client class Real def get_views(params={}) page_params = Zendesk2.paging_parameters(params) request( :params => page_params, :method => :get, :path => "/views.json", ) end end class Mock def get_views(params={}) page(params, :views,...
class EventsController < ApplicationController def index @name = 'RubyKaigi 2020' @date = DateTime.new(2020, 4, 9) @events = Event.all end end
require_relative '../spec_helper' require 'route' RSpec.describe Route do let(:input) { Generator.router(path: "/foo") } it "should parse a route properly" do route = Route.new(input) expect(route.path).to eq("/foo") end end
# # Cookbook Name:: cubrid # Recipes:: shard # # Copyright 2012, Esen Sagynov <kadishmal@gmail.com> # # Distributed under MIT license # include_recipe "cubrid" if node['cubrid']['version'] >= "8.4.3" if node['cubrid']['shard_db'] != "" && !node['cubrid']['shard_hosts'].empty? if node['cubrid']['shard_key_modular']...
# frozen_string_literal: true module CodebreakerVk module Database SEED = 'database.yaml' def load(path = SEED) YAML.load_file(path) end def save(summary, path = SEED) row = TableData.new(summary) if File.exist?(path) table = load(path) table << row File.wr...
# TODO: rename this DM::Symbol::Operator # TODO: add a method to convert it into a DM::Query::AbstractComparison object, eg: # operator.comparison_for(repository, model) # TODO: rename #target to #property_name module DataMapper class Query class Operator include Extlib::Assertions extend Equaliz...
class StockProvision < ActiveRecord::Base STATUSES = %w(nouveau validé reçu annulé).freeze belongs_to :provider has_many :product_provider_stock_provisions, dependent: :destroy has_many :product_providers, through: :product_provider_stock_provisions before_save :init_stock_provision, unless: :special? a...
Rails.application.routes.draw do resources :cuisine, :restaurants, :review root 'application#index' end
class ClientsController < Company::BaseController layout "application" set_tab :clients helper_method :sort_column, :sort_direction def index if params[:tagged] @clients = current_company.clients.tagged_with(params[:tagged]) @clients = @clients.where("lower(irst_name) LIKE :term OR lower(last_n...
class MatchData primitive 'at', 'at:' primitive_nobridge '[]' , '_rubyAt:' primitive '[]' , '_rubyAt:length:' def inspect matches = [self[0]].concat(self.captures) "MatchData: #{matches.inspect}" end def to_a __captures([self[0]]) end def to_s self[0] end def begin(group) at(...
require 'spec_helper' module TwitterCli describe "timeline processor" do conn = PG.connect(:dbname => ENV['database']) context "execute" do it "should process based on username" do conn.exec('begin') timeline_processor = TimelineProcessor.new(conn) allow(timeline_processor).to r...
require 'formula' class SubproZcompletion < Formula homepage 'https://github.com/satoshun/subpro' url 'https://raw.githubusercontent.com/satoshun/subpro/v1.1.0/subpro_zcompletion' sha256 '70c2b2c3d8da6803fd026ddc061e12e955d57f3992c1e6d0cff8c8e40ed2b180' def install (prefix+'etc/zsh_completion.d').install ...
json.array!(@dois) do |doi| json.extract! doi, :id, :doi_num json.url doi_url(doi, format: :json) end
class Bike_Lot < Park ::MaximunBikeCapacity = 20 attr_reader :spaces, :capacity def initialize @spaces = [] @capacity = MaximunBikeCapacity end def park_by_type(vehicle) park_bike(vehicle) if vehicle.type == "Bike" end def park_bike(vehicle) raise 'Bike Park Full' if @bikes.spaces.count...
require_relative 'base_reader' module Tokenizer module Reader class FileReader < BaseReader # Params: # +options+:: available options: # * filename - input file to read from def initialize(options = {}) super() @file = File.open options[:filename], 'r' ...
class ReviewsController < ApplicationController before_filter :authenticate_user! respond_to :json def create @user = User.find(params[:user_id]) if @user.credport_recommendation_written_by(current_user).length > 0 render :json => {:errors => ["You already wrote #{@user.first_name} a recommendat...
ActiveAdmin.register Category do controller do skip_before_action :load_init_data end permit_params :name, :details end
class PostsController < ApplicationController load_and_authorize_resource :except => [:overview, :show, :feed] # GET /posts # GET /posts.json def index authorize! :manage, Post @posts = Post.all respond_to do |format| format.html # index.html.erb format.json { render json: @posts ...
class TeamsController < ApplicationController def index @teams = Team.all end def show @user = current_user if @user.team_id.blank? @team = Team.where(id: params[:id]).first if params[:password] && @team.authenticate(params[:password]) @user.update_attributes(team_id: @team.id) ...
require 'spec_helper' describe "commits/new" do before(:each) do assign(:commit, stub_model(Commit, :committer_email => "MyString", :committer_name => "MyString", :html_url => "MyString", :repository_id => "MyString", :sha => "MyString", :author_name => "MyString", :auth...
describe PersonStarship do describe "associations" do it { is_expected.to belong_to :person } it { is_expected.to belong_to :starship } end end
#!/usr/bin/env ruby -w # Dan Peterson <danp@danp.net> # you can do whatever you want with this file but i appreciate credit # # Refactored by Eric Hodel <drbrain@segment7.net> class RBayes ## # The version of RBayes you are using. VERSION = '1.0.0' # :stopdoc: COUNT_BLAND = " count_bland " COUNT_TASTY ...
require "spec_helper" # http://www.collmex.de/cgi-bin/cgi.exe?1005,1,help,api_Rueckmeldungen describe Collmex::Api::Message do context "Success" do it_behaves_like "an API command" do let(:params) { { type: "S" } } let(:output) { ["MESSAGE", "S", nil, "", nil] } its(:success?) { should eq...
class RenameTableAttributesOptionToAttributeList < ActiveRecord::Migration def change rename_table :attributes_options, :attribute_lists rename_table :attribute_class_options_attributes_options, :attribute_class_options_attribute_lists rename_column :attribute_class_options_attribute_lists, :attributes_op...
require 'simple_assert' module ThinWestLake::Generator # Encapule ERB operation into a single operation module ErbTmpl # Generate a file from a erb template file # # @param src [String] Path of ERB template file # @param dest [String] Generated file path # @param context...
json.array!(@inclusions) do |inclusion| json.extract! inclusion, :id, :product_id, :meditation_id, :creator_id json.url inclusion_url(inclusion, format: :json) end
class Message < ApplicationRecord belongs_to :room belongs_to :user has_one_attached :image validates :content, presence: true, unless: :was_attached? #unlessオプションにメソッド名を指定することで、 #「メソッドの返り値がfalseならばバリデーションによる検証を行う」という条件を作っている def was_attached? self.image.attached? end #self.image.attached?によって、...
require 'yaml' class Gpgenv class Profile attr_reader :file, :name def initialize(file, name) @file = file @name = name end def exec_command(cmd) exec(read_files, cmd) end def read_files hash = {} gpgenvs.each do |gpgenv| hash.merge!(gpgenv.read_files) ...
class User < ApplicationRecord has_many :prophets def self.find_or_create_from_auth(auth) provider = auth[:provider] uid = auth[:uid] name = auth[:info][:name] image_url = auth[:info][:image] user = self.find_or_initialize_by(provider: provider, uid: uid) user.name = name user.image_ur...
class AddRemainingBudgetToAdvertisers < ActiveRecord::Migration def change add_column :advertisers, :remaining_budget, :float,:default=>0 add_column :advertisers, :total_ad_served, :float,:default=>0 add_column :advertisers, :approved,:boolean,:default=>false end end
module Tokenizer class Lexer module TokenLexers def function_def?(chunk) chunk =~ /.+とは\z/ end def tokenize_function_def(chunk) validate_scope( Scope::TYPE_MAIN, ignore: [Scope::TYPE_IF_BLOCK, Scope::TYPE_FUNCTION_DEF, Scope::TYPE_TRY], error_class:...
class FixFossilColumnName < ActiveRecord::Migration[5.1] def change rename_column :fossils, :layers_id, :layer_id end end
class AdviceSerializer < ActiveModel::Serializer attributes :id, :quote, :user end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? layout :layout_by_resource private def layout_by_resource if devise_controller? && (controller_name == "p...
module Api class ReviewsController < ApplicationController def index render json: Review.newest_first, each_serializer: Api::ReviewSerializer end def show render json: Review.find(params[:id]) end def create review = Review.new(review_params) if review.save render...
class Api::V1::FacebookPagesController < Api::V1::BaseController def index account = Account.find(params[:account_id]) if belongs_to_user?(resource: account) respond_with :api, :v1, GetFacebookPages.call(account: account) end end def create account = Account.find(params[:account_id]) ...
require 'digest' require 'uri' require 'net/http' class Blockchain @chain @current_transactions @nodes def initialize @chain = Array.new @current_transaction = Array.new @nodes = Set.new self.new_block(1,100) end """ Create a new Block in the Blockchain :param proof: <int> The proof g...
class Image < ActiveRecord::Base belongs_to :owner, polymorphic: true before_destroy :destroy_at_cloudinary def destroy_at_cloudinary Cloudinary::Uploader.destroy(self.public_id) if self.public_id end def url "http://#{default_cloudinary_url}#{self.public_id}" end def secure_url "https://#{...
require "test_helper" require "minitest/spec" module ActiveRecord::Snapshot class S3Test < ActiveSupport::TestCase extend MiniTest::Spec::DSL let(:fog_connection) { mock("Fog Connection") } describe "::new" do it "creates a fog connection" do ::Fog::Storage.expects(:new) S3.new(di...
require 'rails_helper' RSpec.describe "Admin::Admins", type: :request do before do @admin = create(:admin) end it "ログイン後にadmin専用のdashboardページが表示されること" do sign_in(@admin) get admin_root_path expect(response).to have_http_status "200" end end
FactoryGirl.define do factory :user do username "niles" password "123456" email "niles@nilesrocks.com" cellphone "222-222-2222" end factory :event do user_id 1 title "Lincoln Park Run" description "Easy run along lakeshore drive" route_id 1 start_time "2013-07-10 17:08:23 -05...
module BluetoothInspector # Formats a list of devices for the expected bitbar output. class Formatter def initialize @bar_format = ":shortname :battery%" @item_format = ":name" end # Get the format for a device as a bar item. # # @return [String] attr_reader :bar_format #...
require 'database_helpers' require 'users' describe User do describe '.create' do it 'creates a new user' do user = User.create( name: 'Test user', email: 'test@test.com', password: 'test123' ) pud = persisted_users_data(user_id: user.user_id) expect(user).to be_a ...
require 'faraday' require 'set' module OpticsAgent module Reporting class DetectServerSideError < Faraday::Middleware RETRY_ON = Set.new [500, 502, 503, 504] def call(env) @app.call(env).on_complete do |r| if RETRY_ON.include? env[:status] raise "#{r[:status]} status co...
class Usage < ActiveRecord::Base belongs_to :sample, inverse_of: :usages belongs_to :participation, inverse_of: :usages end
# This mixin helps monitor and manage downloads module DownloadHelper DOWNLOAD_TIMEOUT = 10 DOWNLOAD_PATH = File.expand_path('../../tmp', __FILE__) def downloads Dir[File.join(DOWNLOAD_PATH, '*')] end def download downloads.first end def download_content wait_for_download File.read(down...
module Orthographer class MissResult < Result def to_s "#{super.to_s}: #{suggestions}" end private def splitted_feedback @splitted_feedback ||= @feedback.gsub(/:/, '').split ' ' end def offset splitted_feedback[3] end def original splitted_feedback[1] en...
require "integration/factories/collection_factory" class SubnetworksFactory < CollectionFactory def initialize(example) # We cannot have 2 subnetworks with the same CIDR range so instantiating a # class variable holding a generator, ensuring that the factory gives us a # new subnet every time it's called...
# this is the character's race (aka human, elf, etc.) class Race < ActiveRecord::Base has_many :characters end
require 'spec_helper' describe GroupDocs::Questionnaire do it_behaves_like GroupDocs::Api::Entity include_examples GroupDocs::Api::Helpers::Status describe '.all!' do before(:each) do mock_api_server(load_json('questionnaires_get')) end it 'accepts access credentials hash' do lambda do...
# == Schema Information # # Table name: experiences # # id :integer not null, primary key # year :string(255) # title :string(255) # description :string(255) # kind :integer # post_id :integer # created_at :datetime not null # updated_at :datetime not nul...
require "rails_helper" RSpec.describe Message, :type => :model do context "generate new message" do it "has a title" do message = Message.create(title: "Cute", sender_id: 1, recipient_id: 2) expect(message.title).to eq("Cute") end it "has a name" do message = Message.create(title: "Cu...
module StubDaemon def stub_daemon(running: false, variant: "td-agent") daemon = FactoryBot.build(:fluentd, variant: variant) stub(Fluentd).instance { daemon } any_instance_of(Fluentd::Agent::TdAgent) do |object| stub(object).detached_command { true } stub(object).running? { running } end ...
class Zoo < ActiveRecord::Base has_many :animals, dependent: :destroy validates :name, :location, presence: true end
class RockPaperScissors module GameResult def self.check(player_hand, computer_hand) if player_hand == computer_hand PlayerRecord.record[:tie] += 1 @message = "Computer chose '#{computer_hand}'. It's a tie!" elsif computer_hand == WINNING_HAND[player_hand].winning_hand PlayerRe...
# frozen_string_literal: true module Silkey # :nodoc: all class Contract < SimpleDelegator def initialize(contract, client) super(contract) @contract = contract @client = client _, @functions, = Ethereum::Abi.parse_abi(contract.abi) end def call_func_for_block(func_name, default_...
module WorksHelper def render_table_header(instrument, number = nil) method = number.nil? ? instrument : "#{instrument}_#{number}?" if @workdetail.send(method) "<th>#{instrument.capitalize} #{number || 1}</th>".html_safe end end def render_table_cell(workdetail, instrument, number = nil) me...
require 'bank_account' describe BankAccount do MONEY = 100 default_balance = BankAccount::DEFAULT_BALANCE subject(:bank_account) { BankAccount.new } let(:deposit_transaction) { Transaction.new(100, 100, 'deposit') } let(:withdraw_transaction) { Transaction.new(100, 100, 'withdraw') } it 'is initialized wi...
json.extract! @course, :id, :name, :description json.user do json.id @course.user.id json.email @course.user.email end json.videos @course.videos do |video| json.extract! video, :id, :name, :url end
class AddDriverToOrders < ActiveRecord::Migration[5.1] def change add_column :orders, :driver_id, :integer add_column :orders, :driver_name, :string end end
class PingsController < ApplicationController skip_before_action :verify_authenticity_token def create ActionCable.server.broadcast(:ping_channel, params.to_unsafe_h.except(:controller, :action, :ping)) head :created end end
require 'rails_helper' describe "Signing in" do it "prompts for an email and password" do visit root_url click_link 'Sign In' expect(current_path).to eq(new_session_path) expect(page).to have_field("Email") expect(page).to have_field("Password") end end
=begin Write a method that takes two arguments, a positive integer and a boolean, and calculates the bonus for a given salary. If the boolean is true, the bonus should be half of the salary. If the boolean is false, the bonus should be 0. =end # Option A: def calculate_bonus(salary, bonus_confirmation) bonus = 0 ...
require 'clipper' require_relative 'element' module LibreFrame module ElementFramework # A group of other elements which are drawn on the same "plane" using # boolean operations. This enables the shapes to blend together. class ShapeGroup < StyledElement def draw_child_paths? false ...
class Food < ApplicationRecord belongs_to :user has_many :votes, dependent: :destroy validates :title, :kind, :image, presence: true mount_uploader :image, ImageUploader def Food.random_soup Food.all.where(kind: 'soup').shuffle.first end def Food.random_salad Food.all.where(kind: 'salad').shu...
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action :add_flash_messages_from_params protected helper_method :current_time_zone def current_tim...
module SportsDataApi module Nhl class TeamSeasonStats attr_reader :year, :season, :team, :opponents ## # Creates a new nhl TeamSeasonStats object def initialize(xml) @year = xml['year'] @season = xml['type'] @team = create_team(xml.xpath('team').first) @oppo...
Rails.application.routes.draw do root 'cocktails#index' resources :cocktails do resources :doses, except: :destroy end resources :doses, only: :destroy end
class RingGroup < ApplicationRecord has_one :number, as: :assignable, class_name: "PhoneNumber", dependent: :nullify, inverse_of: :assignable has_many :members, dependent: :restrict_with_error, class_name: "RingGroupMember" has_many :users, through: :members has_many :ring_group_calls, -> { ...
class AddingFieldsPassedpostrepairAndRepairedonsiteForDamperinspection < ActiveRecord::Migration def change add_column :lsspdfassets, :u_di_repaired_onsite, :string add_column :lsspdfassets, :u_di_passed_post_repair, :string end end
# frozen_string_literal: true FactoryBot.define do factory :join_table_gas_simulation_contract do gas_simulation { create(:gas_simulation) } gas_contract { create(:gas_contract) } end end
require File.expand_path("../../config/environment", __FILE__) require "rails/test_help" require "minitest/reporters" Minitest::Reporters.use! DEFAULT_TEST_PASSWORD = "123456".freeze class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml # for all tests in alphabetical order. fixtures :all ...
# frozen_string_literal: true class RemoveChallengeTypeFromChallenges < ActiveRecord::Migration[5.1] def change remove_column :challenges, :challenge_type, :integer add_column :challenges, :max_completions, :integer Challenge.reset_column_information Challenge.find_each do |challenge| chall...
class Mobile < ApplicationRecord has_many :carreservrequests, dependent: :destroy end
class Shift def name 'big shift' end def time '10:00:00' end def ward 'paternaty' end end class ShiftProxy def initialize(shift_obj = nil) @shift_obj = shift_obj end private def access_granted? true # do some logic to check acess end def subject # This delays cr...
require "spec_helper" describe TypeAheadSearch do let(:owner) { users(:owner) } describe ".new" do it "takes current user and search params" do search = described_class.new(owner, :query => 'fries') search.current_user.should == owner search.query.should == 'fries' end end describe ...
module Paperclip module Storage # The default place to store attachments is in the filesystem. Files on the local # filesystem can be very easily served by Apache without requiring a hit to your app. # They also can be processed more easily after they've been saved, as they're just # normal files. The...
require 'rails_helper' describe User, type: :model do describe 'validations' do it {should have_many :reviews} end end
class Bus attr_accessor :route, :destination, :passengers def initialize(route, destination, passengers = []) @route = route @destination = destination @passengers = passengers end def passenger_count @passengers.count end def add_passenger(new_passenger) @passengers.push(new_passenger) end def remove_...
class Geocash < ApplicationRecord PRESHARED_SECRET_BYTE_LENGTH = 128 has_many :transfers, dependent: :restrict_with_error, inverse_of: :geocash before_validation :assign_new_preshared_secret, unless: :preshared_secret? validates :preshared_secret, :description, presence: true def generate_preshared_secret...
require 'rubygems' require 'bundler/setup' require 'yaml' deploy_dir = '_deploy' current_sha = nil gh_pages_branch = 'gh-pages' gh_repo = 'git@github.com:GSA/search.digitalgov.gov.git' desc 'setup jekyll site for deployment' task :setup do rm_r Dir.glob("#{deploy_dir}") system "git clone -b #{gh_pages_branch} #{g...
class InviteMailer < ApplicationMailer def invitation_send(invitation) @invitation = invitation if @invitation != nil && @invitation.email != "" mail to: @invitation.email, subject: "Invitation E-mail" end 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...
class CreateBillings < ActiveRecord::Migration def change create_table :billings do |t| t.timestamp :created_on t.timestamp :updated_on t.string :number t.date :billing_date t.integer :person_id t.decimal :amount, precision: 10, scale: 2 t.decimal :outstanding, precision:...