text
stringlengths
10
2.61M
# frozen_string_literal: true module Vedeu module Cells # Provides the position and visibility escape sequence for a # {Vedeu::Cursors::Cursor} # # @api private # class Cursor < Vedeu::Cells::Empty # @return [NilClass] def null nil end alias background null ...
class Movie < ApplicationRecord validates :title, :description, :rating, :director,:video_url, presence: true validates :rating, inclusion: {in: ['g', 'pg', 'pg-13', 'r', 'not rated']} # has_many :favorites # has_many :users, through: :favorites, source: :user has_and_belongs_to_many :users ...
# frozen_string_literal: true RSpec.describe Devise::DeviseAuthyController, type: :controller do let(:user) { create(:authy_user) } before(:each) { request.env["devise.mapping"] = Devise.mappings[:user] } describe "first step of authentication not complete" do describe "with no user details in the session" ...
class AddTosAcceptTosUsers < ActiveRecord::Migration def change add_column :users, :tos_accept, :boolean end end
json.array! @users do |user| json.name user.nickname json.id user.id end
class StoriesController < ApplicationController before_filter :detect_user before_filter :detect_project def show @story = PivotalPlanningPoker::Story.find(params[:project_id], params[:id], @user.token) create_or_update_game(@story.story_id, @story.estimate) end def update tracker_story = Pivota...
# collector.rb # === Authors # # Sam Dacanay <sam.dacanay@logicmonitor.com> # Ethan Culler-Mayeno <ethan.culler-mayeno@logicmonitor.com> # # Copyright 2016 LogicMonitor, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You ...
class ExerciseSerializer < ActiveModel::Serializer attributes :id, :name, :difficulty, :how, :length belongs_to :category end
require_relative "tree_logger/version" require 'json' module TreeLogger class Record def initialize(library) @library = library @messages = library['records']['messages'] @format = library['records']['format'] @watches = {} @book = Array.new end def record(status, directory...
=begin In an earlier exercise, you wrote a program that prints 'Launch School is the best!' repeatedly until a certain number of lines have been printed. Modify this program so it repeats itself after each input/print iteration, asking for a new number each time through. The program should keep running until the user e...
class AddimgurlToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :imgurl, :string add_column :profiles, :phone, :string end end
class AddCampaigntaglineToCampaigns < ActiveRecord::Migration def change add_column :campaigns, :campaigntagline, :text end end
Rails.application.routes.draw do root "home#index" resources :movies end
class CharacterSpellsController < ApplicationController before_action :set_character_spells, only: %i[show edit update destroy] def index @character_spell_spells = current_user.characters end def new @character_spell = Character.new end def create @character_spell = Character.new(character_pa...
class Group < ApplicationRecord has_many:messages has_many:users,through: :messages end
require 'open-uri' require 'nokogiri' class HTMLFromUrl attr_accessor :url_str def initialize(url_str) @url = url_str end def create html = html_get Nokogiri::HTML(html) end def html_get open(@url) end private def html_get open(@url) end end
class Meal < ActiveRecord::Base belongs_to :breeder has_one :menu end
class WorkPatternsController < ApplicationController # GET /work_patterns # GET /work_patterns.xml def index @work_patterns = WorkPattern.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @work_patterns } end end # GET /work_patterns/1 # GET /work...
class Checker attr_reader :corrected, :original def initialize text @original = text.strip end def total_count regexes.map{ |k, v| send("#{k}_count") }.sum end def total_percent total_count.to_f / original.size.to_f * 100 end [:space, :ellipsis, :z, :s, :h, :k, :capitals].each do |check|...
class Cacheexec < Formula desc "Shell-oriented caching tool, good for complex shell prompt decoration" homepage "https://github.com/jsleeio/cacheexec" url "https://github.com/jsleeio/cacheexec.git", :using => :git, :tag => "v1.0.0", :revision => "8f4f6e954a55f1fdc879c6f4c7f4108e425b912f"...
Rails.application.routes.draw do root 'pages#index' resources :channels do member do get 'on' get 'off' get 'status' end end end
# frozen_string_literal: true require 'jiji/test/test_configuration' require 'jiji/model/securities/internal/examples/trading_examples' if ENV['OANDA_API_ACCESS_TOKEN'] describe Jiji::Model::Securities::Internal::Virtual::Trading do include_context 'use backtests' let(:wait) { 0 } let(:backtest_id) { b...
require 'spec_helper' describe "GroupPages" do subject { page } let(:user) { FactoryGirl.create(:user) } before do visit new_user_session_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Sign in' end describe 'create page' do before { visit ...
require 'rails_helper' RSpec.describe User, type: :model do it "encrypts ssn" do user = User.create!(ssn: "123") expect(user.encrypted_ssn).not_to eq('123') end it "decrypts ssn" do user = User.create!(ssn: "123") expect(user.ssn).to eq('123') end it "uniquely encryptes ssn" do user1 = Us...
class ResponseCode attr_reader :params def initialize (params = {}) @params = params end def code code = params.has_key?("response_code") ? params["response_code"].to_i : 200 code = 200 if code == 0 code 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 rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanue...
Gem::Specification.new do |s| s.name = 'ambihue' s.version = '0.0.1' s.date = '2013-11-23' s.summary = 'AmbiHue' s.description='Enables an Ambilight TV to control the Hue lamps' s.authors = ["Jan-Niklas Meier"] s.email = 'jan@jansblog.org' s.files = ["lib/AmbiHue....
class Article < ApplicationRecord belongs_to :author, class_name: 'User' scope :drafts, -> { where(draft: true) } scope :published, -> { where(draft: false) } scope :recent, -> { published.order(published_at: :desc) } scope :recent_drafts, -> { drafts.order(updated_at: :desc) ...
# == Schema Information # # Table name: runs # # id :integer not null, primary key # run_date :date # distance :float # route_name :string(255) # notes :text # run_time :integer # user_id :integer # class Run < ActiveRecord::Base belongs_to :user before_validation :init_data ...
require 'test/unit' require 'rubygems' gem 'activerecord', '>= 1.15.3' require 'active_record' require "#{File.dirname(__FILE__)}/../init" ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:") def setup_db ActiveRecord::Schema.define(:version => 1) do create_table :mixins_uuid ...
module TrelloPresenter class Board attr_reader :lists, :name def initialize(raw_data) @raw_data = raw_data @name = raw_data['name'] @lists = List.build(raw_data['lists']) Card.build(self, cards: raw_data['cards'], check_lists: raw_data['...
class Point attr_accessor :x, :y def initialize x, y @x = x @y = y end end class Vector attr_accessor :a1, :a2 def initialize @a1 = @a2 = 0 end def setAttributes p1, p2 @a1 = p2.x - p1.x @a2 = p2.y - p1.y end def modifyToAxis swap negativeA1 end def negativeA1 @a1 = -@a...
require "spec_helper" describe Mongoid::IdentityMap do let(:identity_map) do described_class.new end describe "#clear" do before do identity_map.set(Person.new) end let!(:clear) do identity_map.clear end it "empties the identity map" do identity_map.should be_empty ...
module Melon module Posts class Model < Base::Model end class Controller < Base::Controller ## Front Page # # Gets the [key] most recent posts, ordered by date # def frontpage key = 0 key = key.to_i - 1 # This takes care of an omitted `key` value ...
class UrlValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) URI.parse(value) rescue URI::Error record.errors[attribute] << (options[:message] || "is not a valid #{attribute}") end end
# 1. class Geek def initialize @message = "ruby ruby" end def make_some_voice "I like to #{@message}" end end alex = Geek.new puts alex.make_some_voice() =begin => I like to ruby ruby Переменная @message доступнав методе, т.к. является переменной экземпляра, которые доступны всем методам экземпляра. ...
class AddNewColumnsToApplicants < ActiveRecord::Migration def change add_column :applicants, :first_name, :string add_column :applicants, :middle_initial, :string add_column :applicants, :last_name, :string add_column :applicants, :city, :string add_column :applicants, :zip, :string add_column...
# # Author:: Joe Williams (<j@boundary.com>) # Cookbook Name:: apps # Definition:: apps # # Copyright 2011, Boundary # # 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....
Factory.define :user do |user| user.sequence(:email) { |n| "user#{n}test.com" } user.name "User" user.password "password" user.password_confirmation "password" user.avatar "1.jpg" end
namespace :server do desc "kills rails daemon" task kill: :environment do pid_file = 'tmp/pids/server.pid' pid = File.read(pid_file).to_i Process.kill 9, pid File.delete pid_file end desc "kills unicorn daemon" task ukill: :environment do pid_file = '/var/pids/unicorn.pid' pid = File.re...
class UsersLesson < ActiveRecord::Base belongs_to :user belongs_to :lesson has_many :users, through: :users_lessons end
# frozen_string_literal: true require 'spec_helper' describe Darlingtonia::HyraxRecordImporter, :clean do subject(:importer) do described_class.new(error_stream: error_stream, info_stream: info_stream) end load File.expand_path("../../support/shared_contexts/with_work_type.rb", __FILE__) include_context '...
# encoding: UTF-8 # Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 require 'spec_helper' describe TwitterCldr::Localized::LocalizedTimespan do it "should format a numer of seconds in different units" do timespan = described_class.new(-172800, locale: :de) expect(timespan.to_s(unit...
When(/^I quit$/) do @commandProcessor.process("quit") end Then(/^I should stop exploring$/) do expect(true).to(eq(@commandProcessor.isQuitting?)) end
# # Copyright 2013, Seth Vargo <sethvargo@gmail.com> # Copyright 2013, Opscode, 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 # # Unl...
module Testbeds module Rake module DSL def each_testbed if current = Testbeds.current namespace 'testbed:current' do yield current end end Testbeds.each do |testbed| namespace testbed.namespace do yield testbed end ...
class UpdateConfirmedAtForGames < ActiveRecord::Migration def up Game.record_timestamps = false Game.find_each do |game| if game.game_ranks.not_confirmed.count < 1 game.update_attributes!(:confirmed_at => game.game_ranks.order('confirmed_at DESC').first.confirmed_at) end end Game.r...
require 'rails_helper' RSpec.describe NagerDateService do before :each do @mock_response = "[{\"date\":\"2021-09-06\",\"name\":\"Labour Day\"}, {\"date\":\"2021-10-11\",\"name\":\"Columbus Day\"}, {\"date\":\"2021-11-11\",\"name\":\"Veterans Day\"}, ...
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'colorpress/version' Gem::Specification.new do |spec| spec.name = 'colorpress' spec.version = Colorpress::VERSION spec.authors = ['Luc Street'] spec.summary = 'Visualize arbitrary files a...
feature 'Removing an user' do scenario do user = create(:user) sign_in_as_admin expect { visit user_path(user) click_link 'Remove' }.to change(User, :count).by(-1) end end
class CreasicException < StandardError attr_reader :mensaje, :errores def initialize(mensaje, errores) super mensaje @mensaje = mensaje @errores = errores end end
Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions', reviews: 'api/v1/reviews', index: '/users' } # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'homepage#index' resources :homepage resource...
class StaticPagesController < ApplicationController before_action :authenticate, :except => [:index] def index @updateAssetMap = { Update::Type::PAPER.to_s => ActionController::Base.helpers.asset_url("paper_update.png"), Update::Type::AWARD.to_s => ActionController::Base.helpers.asset_url("award_up...
json.array!(@artists) do |artist| json.extract! artist, :id, :email, :twitter, :facebook, :nickname, :name, :state, :city, :portafolio_1, :portafolio_2, :portafolio_3 json.url artist_url(artist, format: :json) end
# frozen_string_literal: true RSpec.describe J8::Consumer do before(:each) do @tracker = OpenStruct.new @consumer = J8::Consumer.new(->(object) { @tracker.tracking = object }) end describe '.new' do context 'when given a valid callable' do it 'then creates a new consumer' do expect(@co...
module MomentumCms module Tags class CmsHtmlMeta < CmsBaseTag def initialize(tag_name, params, tokens) super @params['type'] = 'css' if tag_name == 'cms_css' @params['type'] = 'js' if tag_name == 'cms_js' end def render(context) cms_page = context_get!(context, ...
# frozen_string_literal: true require 'spec_helper' require 'json' require 'tmpdir' describe 'get' do include CliIntegration let(:proxy) { Billy::Proxy.new } let(:dest_dir) { Dir.mktmpdir } let(:git_dir) { Dir.mktmpdir } let(:git_uri) { "file://#{git_dir}" } before { proxy.start } after { proxy.res...
class Repeat < ActiveRecord::Base has_many :meetings end
class OrderableSet include Mongoid::Document ################################ # Mongoid relation definitions # ################################ belongs_to :orderable_set_count belongs_to :group_buy embeds_many :orderable_set_price_tiers # embeds_many :orderable_items ############################# ...
require File.expand_path('helper/bootstrap', File.dirname(__FILE__)) describe Airstream::Player do before do @device = MiniTest::Mock.new end describe "when no files are given" do it "should be finished" do player = Airstream::Player.new(@device, []) assert player.finished? end end ...
class Model::Page::HomePage < SitePrism::Page set_url "#{Helpers::Config['pf_site_root']}" element :createcourse,'a[href="Course/CreateCourse"] h2' element :find_examurl, 'a[href="Exam/FindExam"] h2' #findcourseurl is repeated twice on the page, so use .first and .last in the step defs elements :find_course...
require 'test_helper' class StaticPagesControllerTest < ActionController::TestCase test "should get home" do # Let’s test the Home page by issuing a GET request to the home action and # then making sure we receive a ‘success’ status code in response get :home assert_response :success # the asser...
class CsvImportsController < ApplicationController before_action :set_csv_import, only: [:show, :edit, :update, :destroy] # GET /csv_imports # GET /csv_imports.json def index @csv_imports = CsvImport.all end # GET /csv_imports/1 # GET /csv_imports/1.json def show end # GET /csv_imports/new ...
FactoryGirl.define do factory :article do title content { Faker::Lorem.paragraph(10) } privated { false } user end end
#!/usr/bin/env ruby # encoding: utf-8 describe "Macro:" do before do create_project Glyph.run! 'load:all' end after do Glyph.lite_mode = false delete_project end it "snippet" do define_em_macro interpret "&:[test|This is a \nTest snippet]Testing a snippet: &[test]." expect(@p.document.output).to ...
require 'rails_helper' RSpec.describe BuyHistory, type: :model do describe '#create' do before do @item = FactoryBot.create(:item) @user = FactoryBot.create(:user) @buy_history = FactoryBot.build(:buy_history, item_id: @item.id, user_id: @user.id) sleep 1 end context '購入ができる時' do ...
class DropCreditorColumnFromDebits < ActiveRecord::Migration def self.up remove_column :debits, :creditor_id remove_column :debits, :debtor_id add_column :debits, :member_id, :integer end def self.down raise IrreversibleMigration end end
# frozen_string_literal: true require 'spec_helper' describe SFRest::Task_log_settings do before :each do @conn = SFRest.new "http://#{@mock_endpoint}", @mock_user, @mock_pass end describe '#get_task_log_settings' do path = '/api/v1/task-log-settings' it 'calls the task log settings get endpoint' ...
require 'rails_helper' RSpec.feature "About page transition", type: :feature do before do @user = FactoryBot.create(:user) end feature 'home page' do before do visit root_path end it 'homeにWelcome to the Naokis Book Store文字が現れる' do expect(page).to have_content "Welcome to the Na...
require "bundler/gem_tasks" require 'rake' require 'rdoc/task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new desc 'Default: run spec.' task :default => :spec lib = File.expand_path('../lib/', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'billtrap/version' Rake::RDocTask.new do ...
module Response def json_response_object(object, status = :ok) render json: object, status: status end def json_response_message(message, status = :ok) render json: { message: message }, status: status end end
# rubocop:disable Rails/Output if ENV['ADMIN_EMAIL'].present? && ENV['ADMIN_PASSWORD'].present? user = User.create( role: 'admin', email: ENV['ADMIN_EMAIL'], password: ENV['ADMIN_PASSWORD'], password_confirmation: ENV['ADMIN_PASSWORD'], full_name: ...
class Chatbot::ButtonGroup include ActiveModel::Model include Speechable attr_accessor :buttons, :disable_on_click validates :buttons, presence: true, length: { maximum: 12, too_long: I18n.t('errors.chat_statement.buttons.too_long') } validates :disable_on_click, inclusion: { in: [true, false] }, allo...
require 'rails_helper' RSpec.describe Setting, type: :model do it { should validate_presence_of(:slug) } it { should validate_uniqueness_of(:slug) } it { should validate_presence_of(:config_key) } it { should validate_uniqueness_of(:config_key) } it { should validate_presence_of(:config_value) } it { sh...
# == Schema Information # # Table name: photos # # id :integer not null, primary key # created_at :datetime # updated_at :datetime # attachment_file_name :string(255) # attachment_content_type :string(255) # attachment_file_size :integer # attachment_...
class Openssh < Package desc 'Command line and full screen utilities for browsing procfs' homepage 'https://www.openssh.com' url 'git@git.crystax.net:android/vendor-openssh.git|git_commit:f021ec58c66ae1c1ac4d7850d761b7f46a5714ff' url 'https://github.com/crystax/android-vendor-openssh.git|git_commit:f021ec58c66...
class ChunksController < ApplicationController before_action :load_entities def create @chunk = Chunk.create user: current_user, chunk_feed: @chunk_feed, title: params[:title], duration: params[:duration] if @chunk.save du...
class GiftsController < ApplicationController before_filter :authenticate_user! # GET /gifts # GET /gifts.xml def index @user_id = params[:user_id] @user = User.find_by_id(params[:user_id]) @gifts = Gift.paginate :conditions => {:user_id => params[:user_id]}, :page => params[:page], :order => ...
require "./lib/Lesson 4 Counting Elements/PermCheck/permutation_check" describe 'PermCheck' do describe 'Example Tests' do context 'example1' do it 'the first example test - [4, 1, 3, 2]' do expect(permutation_check([4, 1, 3, 2])).to eq 1 end end context 'example2' do it 'the s...
class QuestionLike def self.all results = QuestionsDatabase.instance.execute('SELECT * FROM question_likes') results.map { |result| self.class.new(result) } end attr_reader :id, :user_id, :question_id def initialize(options = {}) @id = nil @question_id = options['question_id'] @user_id = o...
# Linked List practice class LinkedList include Enumerable attr_accessor :name def initialize @head = nil @tail = nil end def each return nil if @head.nil? node = @head until node.nil? yield node node = node.next_node end end def append(node) # adds a...
class CreateMoviesTable < ActiveRecord::Migration[6.0] def change create_table :movies do |t| t.string :name t.references :genre, foreign_key: true t.string :rating t.integer :year t.string :cast t.float :star_rating end end end
class Artist attr_accessor :songs, :name def initialize (name) @name = name @songs = [] end def songs @songs end def genres @songs.collect { |song| song.genre } end def add_song (song) @songs << song song.artist = self end end
require 'builder' module Spree module ExportHelper extend CdataHelper DATE_FORMAT = '%m/%d/%Y %H:%M'.freeze # rubocop:disable all def self.address(xml, order, type) name = "#{type.to_s.titleize}To" address = order.send("#{type}_address") cdata = cdata_helper_for(xml) xml._...
class Group < ApplicationRecord has_many :group_users has_many :messages, dependent: :delete_all has_many :users, through: :group_users, dependent: :delete_all def show_message message = self.messages.first self.messages.first.present? ? message.body : false end end
# require 'byebug' # exercism 5 class Series attr_accessor :slice_string def initialize(slice_string) @slice_string = slice_string.chars end def slices(slice_of_size) raise ArgumentError if slice_of_size > @slice_string.length @slice_string.each_cons(slice_of_size).map(&:join) end end
module Webcore class Engine < ::Rails::Engine isolate_namespace Webcore initializer "action_mailer_auto_url_options.controller" do |app| ActionController::Base.send :include, Webcore::Controller end initializer "webcore.assets.precompile" do |app| config.assets.precompile += %w( webcore/*.p...
require 'level' require 'item' require 'character' require 'command' require 'globals' require 'map' require 'SDLPlugin' class MessageBuffer attr :maxMessages, true attr :lastMessageRead, true def initialize @messages = [] @maxMessages = 5 @lastMessageRead = 0 end def wrapString(...
class RemoveAndReplaceTypeColumn < ActiveRecord::Migration[5.0] def change remove_column :subscriptions, :account add_column :subscriptions, :account, :string end end
class Palindromes attr_accessor :arr def initialize(args) @max_factor = args[:max_factor] @min_factor = args[:min_factor] @arr = [] end def generate first_factor = @max_factor if @min_factor == nil while first_factor != 0 second_factor = first_factor loop do ...
class SiteScraper def initialize(site) @site = site end def scrape! @site.set_scrape('scraping') verify_directories puts "Running #{wget_command} ..." system("cd #{scrape_dir}; #{wget_command}") SiteParser.new(@site).parse! rescue @site.set_scrape('fail') end def log_file ...
# encoding: utf-8 require "helper" describe T::Editor do context "when editing a file" do before do allow(described_class).to receive(:edit) do |path| File.binwrite(path, "A tweet!!!!") end end it "fetches your tweet content without comments" do expect(described_class.gets).to...
# def title_case(title) # split_sentence = title.split # split_sentence.each do |word| # word.capitalize!() # end # split_sentence.join(" ") # end class String def leetspeak array_self = self.split(" ") new_array = [] array_self.each do |array_element| edited_self = array_element.gsub("e", "3")...
require 'tweetstream' require 'twitter' require 'yaml' module CureMuno module_function class CureMuno attr_accessor :config, :client, :stream, :screen_name def initialize config = YAML.load(open(File.dirname(__FILE__) + '/config.yml')) @screen_name = config['screen_name'] @client = Tw...
class TeamsController < IdentityAssociationsController def target_class_name 'identity_association' end protected def render_target render_target_form({}, {:controller => :teams}) end def redirect_after_destroy redirect_after_record end end
module Kramdown module Parser module Denden LINE_BREAK = /\n(?=\S)/ def parse_denden_line_break @src.pos += @src.matched_size @tree.children << Element.new(:br) end Kramdown.define_parser :denden_line_break, LINE_BREAK, '\n(?=\S)' end end end
require "rails_helper" RSpec.describe "Cart", type: :system, js: true do let!(:product) { create(:product) } example "Cartに商品を追加できること" do visit "/" within("#aside-cart") { expect(page).not_to have_content product.title } expect { click_button "Add to Cart" within("#aside-cart") do ...
require 'cf_spec_helper' describe 'When running detect script' do context 'project root directory has Gemfile' do before do root_dir = Dir.pwd Dir.chdir('./cf_spec/fixtures/rails4_web_app') do @output = `#{root_dir}/bin/detect $PWD 2>&1` end end it 'displays the current ruby b...
json.array!(@donations) do |donation| json.extract! donation, :id, :challenge_id, :companyName, :paypalAccount, :amount json.url donation_url(donation, format: :json) end
class Api::ActorsController < ApplicationController def index @actors = Actor.all.order(age: :desc) render 'index.json.jbuilder' end def create @actor = Actor.new( first_name: params[:first_name], last_name: params[:last_name], known_for: params[:known_for], gender: params[...