text
stringlengths
10
2.61M
class PostsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] before_action :correct_user, only: :destroy def show @post = Post.find(params[:id]) @attached_photos = @post.attached_assets.order('post_id ASC').take(1) end def new @post = Post.new end def edit @post...
require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'tmpdir' require 'fileutils' require 'stringio' require 'etc' PhusionPassenger.require_passenger_lib 'message_channel' PhusionPassenger.require_passenger_lib 'platform_info/ruby' PhusionPassenger.require_passenger_lib 'loader_shared_helpers' Phus...
module Bootcamp class BoxPrinter attr_accessor :box def initialize(box) @box = box end def render result = "" (0..@box.sizeY - 1).each do |_y| (0..@box.sizeX - 1).each do |_x| result+= @box.symbol.to_s end result+="\n" end return result ...
require 'spec_helper' describe "reschedulings/index.html.erb" do before(:each) do assign(:reschedulings, [ stub_model(Rescheduling), stub_model(Rescheduling) ]) end it "renders a list of reschedulings" do render end end
class Users::SessionsController < Devise::SessionsController # before_action :configure_sign_in_params, only: [:create] layout "landing", :only => [ :new ] def new super User.new end def create super end def destroy super end # protected # If you have extra params to permit, append ...
class Braille attr_accessor :message, :letter_library, :number_library def initialize @message = File.open(ARGV[0], "r").read.chomp @letter_library = {"a" => ["0.","..",".."], "b" => ["0.","0.",".."], "c" => ["00","..",".."], "d" => ["00",".0",".."],"e" => ["0.",".0",".."], "f" => ["0...
require 'rails_helper' describe '投稿のシステムテスト', type: :system do let(:user_a) { FactoryBot.create(:user, name: 'ユーザーA', email: 'a@example.com', image: 'inu.png') } let(:user_b) { FactoryBot.create(:user, name: 'ユーザーB', email: 'b@example.com', image: 'inu2.png') } let!(:post_a) { FactoryBot.create(:post, content: '...
class App < Sinatra::Base register Sinatra::Namespace # Begin users namespace namespace '/users' do def validate_body_for_create_user begin schema = {"required" => ["email", "first_name", "last_name", "role"] } JSON::Validator.validate!(schema, body_params) rescue Exception => e ...
#!/bin/env ruby # encoding: utf-8 require 'page-object' require 'pry' # require 'selenium/webdriver' class AdminPage include PageObject page_url 'http://dev:1337dev@anuser.onederlink.7bits.it/admin' text_fields(:promo, css: ".form-control") buttons(:delete , css: ".btn.btn-default.promo-list-item.de...
require 'simplecov' require 'paperclip/matchers' # Run code coverage and save to CircleCI's artifacts directory if we're on CircleCI if ENV['CIRCLE_ARTIFACTS'] SimpleCov.coverage_dir(File.join(ENV['CIRCLE_ARTIFACTS'], 'coverage')) end SimpleCov.start 'rails' RSpec.configure do |config| unless ENV['CI'] config...
# frozen_string_literal: true module MideaAirCondition # Device representation (now only for status parsing) class Device attr_reader :data def initialize(data) @data = data @pointer = 0x33 end def power_status !(@data[@pointer] & 0x01).zero? end def temperature (...
Gem::Specification.new do |s| s.name = 'RaaS' s.version = '0.0.6' s.executables << 'RaaSCLI' s.date = '2015-02-22' s.summary = "VMware vCloud Air RaaS program" s.description = "A set of tools that allows VMware vCloud Air customers to interact programmatically with RaaS - Recovery as a...
class FixTimesTable < ActiveRecord::Migration def change rename_table :times, :sessions end end
require 'rails_helper' require 'rake' describe 'utils rake tasks' do before do Rake.application.rake_require 'tasks/utils' Rake::Task.define_task(:environment) end describe 'utils:get_status', type: :request do subject { Rake::Task['utils:get_status'].reenable Rake::Task['utils:get_statu...
class Education < ApplicationRecord belongs_to :applicant has_many :subjects, dependent: :destroy validates :place, presence: true validates_date :end_date, on_or_after: :start_date default_scope { order start_date: :desc } end
require 'pry' require 'pry-byebug' class Apartment attr_accessor :name, :sqft, :bedrooms, :bathrooms, :renter, :rent def initialize(name,sqft,bedrooms,bathrooms) @name = name @sqft = sqft @bedrooms = bedrooms @bathrooms = bathrooms @renter = nil @rent = nil end def to_s #replaces to_s...
class AsaltoSerializer < ActiveModel::Serializer attributes :id,:location,:descripcion def id object._id.to_s end end
def line(arr) return puts "The line is currently empty." if arr.empty? string = "The line is currently:" arr.each_with_index do |name, idx| string += " #{idx + 1}. #{name}" end puts string end def take_a_number(arr, name) arr << name puts "Welcome, #{name}. You are number #{arr.index(name) + 1} in li...
require_relative '../../test_helper' class FixtureSiteTest < ActiveSupport::TestCase def setup @export_path = File.join(Rails.root, 'sites', 'example-c') FileUtils.rm_rf(@export_path) if File.exist?(@export_path) end def teardown FileUtils.rm_rf(@export_path) if File.exist?(@export_path) end d...
# Compress css files with frontmatter headers Jekyll::Hooks.register :pages, :post_render do |page| # only operate on css files if page.ext == '.css' then config = page.site.config @asset_style = config['page_css']['style'] || false # css minification converter_config = { 'sass' => { 'style' => @as...
class AddDetailsToFabrics < ActiveRecord::Migration def change add_column :fabrics, :name, :string add_column :fabrics, :fabric_type, :string add_column :fabrics, :price, :number add_column :fabrics, :quantity, :text add_column :fabrics, :sizes, :text add_column :fabrics, :color, :string a...
# rubocop:disable Metrics/ModuleLength module ApplicationHelper include LayoutHelper ADMIN_CONTROLLERS = ['supply_teachers/admin', 'management_consultancy/admin', 'legal_services/admin'].freeze PLATFORM_LANDINGPAGES = ['', 'legal_services/home', 'supply_teachers/home', 'management_consultancy/home', 'apprentices...
class TrainingSessionsController < Api::V1::ApiController def index @training_sessions = TrainingSession.all end def show; end def update if @training_session.update(training_sessions_params) render 'show', status: :ok else render status: :unprocessable_entuty end end def crea...
#!/usr/bin/env jruby require 'java' require 'set' require 'ir_distance' require 'MQFuzzyRanker' import 'edu.uci.ics.jung.graph.Vertex' import 'abstractor.util.FileUtilities' import 'abstractor.cluster.mq.MQClusterer' import 'edu.uci.ics.jung.graph.Graph' import 'design.model.Design' import 'DummyDoclet' def list...
# frozen_string_literal: true require 'bolt/transport/sudoable/tmpdir' module Bolt module Transport class Sudoable < Base class Connection attr_accessor :target def initialize(target) @target = target @run_as = nil @logger = Logging.logger[@target.safe_name] ...
class Tag < ActiveRecord::Base validates :name, presence: true, uniqueness: true has_many :question_tags has_many :user_tags has_many :questions, through: :question_tags has_many :users, through: :user_tags end
class Supplier < ApplicationRecord belongs_to :category rails_admin do list do items_per_page 100 field :name field :resume field :category do searchable :description pretty_value do value.try(:description) end ...
class Comment < ApplicationRecord belongs_to :article def nice_commenter Array.new(1000).map {|x| 0 } commenter end end
require 'rails_helper' describe 'Catalog List', type: :feature do before do create_list(:book, 30) visit books_path end context 'Show Catalog List' do scenario 'contains 12 elements on page' do expect(page).to have_selector('.col-xs-6.col-sm-3', count: 12) end scenario 'book...
json.array!(@salarieds) do |salaried| json.extract! salaried, :id, :workplace, :profession json.url salaried_url(salaried, format: :json) end
json.array!(@theses) do |thesis| json.extract! thesis, :id, :person_id, :speciality, :council, :theme, :ttype, :year, :in_time, :defence_date, :council_code json.url thesis_url(thesis, format: :json) end
module Control class PlantFeaturesController < ControlPanelController # GET /plant_features # GET /plant_features.json def index @plant_features = PlantFeature.order("#{sort_column} #{sort_direction}") respond_to do |format| format.html # index.html.erb format.json { render js...
class Api::V1::BreedsController < ApplicationController skip_before_action :authorized def index breeds = Breed.breeds render json: breeds end end
require 'rails_helper' RSpec.describe Comment, type: :model do describe 'Require validations' do it 'should has a content' do should validate_presence_of(:content) end end describe 'Has Associations' do it 'belongs to timeline' do should belong_to(:timeline) end it 'belongs to c...
class ResetPasswordsController < ApplicationController skip_load_and_authorize_resource logout :except => [] skip_login def new end def create user = User.where("lower(email) = ?", params[:reset_password][:email].downcase).first if user UserMailer.reset_password(user, user.reset_password!).d...
require 'spec_helper' describe UserVote do context 'without user_id or link_id or vote_val' do let(:incomplete_uservote) { uservote1 = UserVote.new } it "validates presence of link_id" do expect(incomplete_uservote).to have(1).error_on(:link_id) end it "validates presence of user_id" do ...
class DropArchesTable < ActiveRecord::Migration def change drop_table :archived_emails end end
class TransactionsController < ApplicationController def show @transactions = Transaction.all.order('tr_date desc').limit(10) end def new @user = User.new end end
class StationsController < ApplicationController def index stations = Station.where(major: params[:majors], minor: params[:minors]).to_a render json: { stations: stations.map{|s| StationSerializer.new(s)} } end def show render json: StationSerializer.new(station).to_json end private def station @s...
class Stock < ApplicationRecord belongs_to :product validates :count, presence: true, :numericality => { :greater_than_or_equal_to => 0 } end
class NewsletterSignupController < ApplicationController before_action :create_reader, only: [:create] before_action :fetch_reader, only: [:destroy] def create if @tuesday_reader.save flash[:notice] = "Successful Subscribed to Tuesday Newsletter!" else flash[:alert] =...
module SDC module Data # If an actual symbol is not needed, e.g. for one-time draw routines SYMBOL_PREFIX = "_UNKNOWN_" extend SDCMeta::DataStorage self.define_new_data_type(:entity, plural: :entities) self.define_new_data_type(:font) self.define_new_data_type(:text) self.define_new_data_type(:tileset...
class Plate < ActiveRecord::Base mount_uploader :photo, PhotoUploader has_many :options has_many :questions belongs_to :truck has_many :plate_cart_connections has_many :carts, :through => :plate_cart_connections accepts_nested_attributes_for :questions, allow_destroy: true scope :visible, -> { where(so...
class CreateLogradouros < ActiveRecord::Migration def change create_table :logradouros do |t| t.string :nome t.string :cep t.string :num_inicio t.string :num_fim t.timestamps null: false end end end
# -*- coding: utf-8 -*- MESSAGE = { EXIST_1: 'E9001: %s: 既にファイルが存在しています。', NO_EXIST_1: 'E9002: %s: 存在しません。', NO_ACCESS_1: 'E9003: %s: アクセスできません。', BAD_TYPE_1: 'E9004: %%s: ファイル内容が %s です。', BAD_ENCODING_1: 'E9005: %%s: ファイルの ecndoing が utf8 でありません。%s と判定しました。', BAD_TYPE_2: 'E90...
Rails.application.routes.draw do resources :posts get '/posts/:id/body', to: 'posts#body' end
json.array!(@project_statuses) do |project_status| json.extract! project_status, :id json.url project_status_url(project_status, format: :json) end
class RoutesController < ApplicationController respond_to :json def index @routes = Route.all end def show if params[:direction] @route = Route.where(:uid => params[:id, :dir2=>params[:direction]]).first else @route = Route.where(:uid => params[:id]).first end end end
class CreateProjectFields < ActiveRecord::Migration def up unless ::Refinery::ProjectField.table_exists? create_table ::Refinery::ProjectField.table_name, :force => true do |t| t.string :title t.string :value t.integer :refinery_project_id t.integer :position t.timest...
class SessionsController < ApplicationController respond_to :html def create auth = request.env["omniauth.auth"] @user = User.find_by_provider_and_dailymile_id(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth) @user.update_attributes(:image_url => auth['user_info']['image']) sess...
class CreditCard < ActiveRecord::Base belongs_to :wholesaler validates_presence_of :card_type, :card_number, :card_verification_value, :card_expires_on, :address1, :city, :state, :zip, :country def after_create if wholesaler wholesaler.credit_cards.each { |i| return if i.default } self.defau...
class Company < ApplicationRecord validates :name, presence: true has_many :users has_many :categories has_many :ingredients has_many :recipes end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html namespace :api, defaults: {format: :json} do resources :users, only: [:create, :show] do get '/portfolio', :to => 'portfolio_items#index' post '/portfolio', :to => 'p...
class AddScoreToProduct < ActiveRecord::Migration[5.0] def change add_column :products, :score, :integer, default: 0 end end
class AddValueToTags < ActiveRecord::Migration def change add_column :tags, :value, :string add_index :tags, :value add_index :tags, :field add_index :tags, :photo_id end end
class Iteration # returns an array of all the factors of a number def factors(num) divisible_nums = [] (1..num).each do |denominator| divisible_nums << denominator if num % denominator == 0 end divisible_nums end # sorts an array via the bubble_sort algorithm def bubble_sort(unsorted_...
class Challenge < ActiveRecord::Base has_many :challengeRequests, class_name: "ChallengeRequest" has_many :challengeResponses, class_name: "ChallengeResponse" has_many :donations, class_name: "Donation" belongs_to :user, foreign_key: "user_id", class_name: "User" belongs_to :organization, foreign_key: "organization_id...
require_relative '../common/temporal_attributes' require_relative 'proximal_dendrite' require_relative 'cell' require 'forwardable' class Column include Inspector include TemporalAttributes extend Forwardable CELL_COUNT = 4 INPUT_SIZE = 30 DESIRED_LOCAL_ACTIVITY = 3 def_delegators :@htm, :inhibition_r...
class TaskLog < ActiveRecord::Base # ensure task has a name validates :task_id, presence: true # default order to id default_scope { order(id: :desc) } # log record is a child of a task belongs_to :task # keep control over available statuses reported EXC_STATUS = [ "Success", "Fail" ] # display execut...
class Team attr_accessor :name ,:motto @@all=[] def initialize(hash) @name=hash[:name] @motto=hash[:motto] @@all<<self end def self.all @all end end
class Music < ApplicationRecord attachment :musicimage belongs_to :user has_many :music_comments ,dependent: :destroy has_many :favorites ,dependent: :destroy def favorited_by?(user) favorites.where(user_id: user.id).exists? end def self.search(keyword) where(["music_name ...
class StateMachine include HTTParty include Auth0Service base_uri Rails.configuration.environment.fetch("patient_state_api") def self.validate(patient_id, target_state) begin options = { headers: {'Authorization' => "Bearer #{token}", 'Content-Type' => 'application/json' }, body:...
#! /usr/bin/ruby require 'thor' class SayHi < Thor desc "hi NAME", "say hello to NAME" def hi(name) puts "Hi #{name}!" end end class FileOp < Thor desc 'output FILE_NAME', 'print out the contents of FILE_NAME' option :stderr, :type => :boolean def output(file_name) #options[:stderr] is either t...
require 'rails_helper' RSpec.feature 'Page', type: :feature do context 'with no authentication' do before { create :page, slug: 'testing-page', title: 'Some page' } scenario 'is visible' do visit '/testing-page' expect(page).to have_text 'Some page' end scenario 'cannot be created' do ...
require 'spec_helper' describe Plan do before { @subscription = Plan.new(level: "Basic", price: 299.99, number_of_releases_per_month: 5, storage_space: "20 GB", number_of_user_accounts: 10, description: "Awesome", active: true) } subject { @subscription } it { should respond_to(:active) } it { should res...
require 'spec_helper' describe PhotosController do describe "GET index" do before :each do @photos = create_list :photo, 50 @page_size = PhotosController::PHOTOS_PER_PAGE end it "assigns @gallery" do get :index expect(assigns(:gallery)).to_not be_nil end context "wh...
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def span_class person, param "<span class=\"#{param}\">"+ h(person.__send__(param)) +"</span>" end def user_list location if location.listup "<ul>\n#{render :partial => 'locations/user', :...
# encoding: utf-8 # # © Copyright 2013 Hewlett-Packard Development Company, L.P. # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
require 'spec_helper' describe Jekyll::Commands::Gitlab::Letsencrypt do describe '#init_with_program' do let(:prog) { double 'prog' } let(:command) { double Jekyll::Command } it 'calls out to the class' do expect(prog).to receive(:command).with(:letsencrypt).and_yield command expect(comma...
class AddCancelToEventAttendeeAndEventViewer < ActiveRecord::Migration[5.2] def change add_column :event_attendees, :canceled, :boolean, default: false add_column :events, :viewer, :string end end
require 'rails_helper' RSpec.feature 'User logs out', type: :feature do scenario 'when user clicks the sign out link' do sign_in find_link('Sign Out').click expect(page).to have_content 'You have logged out' end end
class FavoriteSerializer < ActiveModel::Serializer # belongs_to :user # belongs_to :gif attributes :user_id, :gif_id, :caption end
class BankTransactionsController < ApplicationController before_action :set_bank_transaction, only: [:show, :reconciliation] def index @bank_transactions = BankTransaction.includes(:bank_statement, :reconciliation).all end def show end def reconciliation if account_exists? if @bank_transact...
require 'rails_helper' RSpec.describe LineItem, type: :model do context "has associations" do it { should belong_to :shopping_cart } it { should belong_to :product} end end
require_relative './constants.rb' require_relative './parser.rb' require_relative './file_handler.rb' require_relative './players_rating.rb' require_relative './show_status.rb' class PlayerScraper < Parser include ShowStatus DIR_TYPE = 'CLUBS'.freeze SITE = 'https://fbref.com'.freeze def initialize(league) ...
#!/usr/bin/env ruby require_relative 'ADAlgorithm' class AddOptional < ADAlgorithm def apply(*args) parent = args[0] child = args[1] p = BasicExpression.new(parent) c = BasicExpression.new(child) [ImpliedExpression.new([c, p])] end end
require 'spec_helper' describe Job::AudioVisionCache do describe '::perform' do before :each do stub_request(:get, %r{billboards/current}).to_return({ :content_type => 'application/json', :body => load_fixture('api/audiovision/billboard1_v1.json') }) end it 'caches the first ...
# coding: utf-8 class Garden < Papartlib::PaperTouchScreen include Lego def settings @tile_width = 16 @tile_height = 12 @tile_size = duplo_size / 1.5 setDrawingSize @tile_width * @tile_size, @tile_height*@tile_size # loadMarkerBoard(Papartlib::Papart::markerFolder + "A4-default.svg", loadMar...
class Users::RegistrationsController < Devise::RegistrationsController def new_guest user = User.guest sign_in user flash[:success] = 'ゲストユーザーとしてログインしました。' redirect_to user_path(user) end end
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # Shindo.tests("Fog::Storage[:softlayer] | File model", ["softlayer"]) do pending unless Fog.mocking? tests("success") do @storage = Fog::Storage[:softlayer] @...
class CatalogPage < ActiveRecord::Base acts_as_list has_attached_file :image, bucket: 'porthos', # convert_options: { all: '-strip -auto-orient -colorspace sRGB' }, default_style: :medium, path: ":rails_root/public...
class PatientsController < SecuredController skip_before_action :authorize_request, only: [:create] def initialize super @patient_service = PatientsService.new end def create patient = @patient_service.create(patient_params) render json: patient end def get patient = @patient_service....
module Maini module Auth class Device < ActiveRecord::Base belongs_to :user def ensure_authentication_token if authentication_token.blank? self.authentication_token = generate_authentication_token end end def generate_authentication_token loop do ...
# Encoding: utf-8 And /^I tap the Favourites CTA$/ do $general.scroll(@favourites.favIcnPLP_element) @favourites.favIcnPLP_element.when_visible.click sleep 2 end When /^I tap the Favourite icon on PDP page$/ do $general.scroll(@favourites.favIcnPDP_element) @favourites.favIcnPDP_element.when_visible.click ...
class ClueSerializer < ActiveModel::Serializer attributes :id, :word, :image end
module Api class TimersController < ::ApplicationController def index timers = [Timer.first_active].compact render json: ActiveModel::ArraySerializer.new(timers, each_serializer: TimerSerializer, root: :timers).to_json end def create timer = Timer.new timer.calculate_end_date(crea...
module EARMMS::SystemConfigurationHelpers def edit_error_page(msg) flash(:error, msg) @title = "System configuration" haml :'system/config/edit' end end
class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem # render new.rhtml def new end def create cookies.delete :auth_token # protects against session fixation attacks, wreaks havoc with # reques...
class UnauthenticatedController < ApplicationController def index render text: 'success' end end
require File.dirname(__FILE__) + '/../../../test_helper' class TinyCI::Shell::LocalhostTest < ActiveSupport::TestCase test "should return false for exists? if working dir does not exist" do working_dir = '/some/dir' File.expects(:exists?).with(working_dir).returns(false) localhost = TinyCI::Shell::L...
class RoomCarouselAnswer < Answer before_save :change_defaults private def make_messages(user = nil) [ { text: message }, { attachment: { type: "template", payload: { template_type: "generic", elements: Room.all.map do |room| { ti...
require 'digest' class User < ActiveRecord::Base has_many :swatches, :dependent => :destroy has_many :colors, :through => :swatches attr_accessor :password attr_accessible :username, :email, :password, :password_confirmation # scope :public, select('username') validates_presence_of :username ...
class Game < ActiveRecord::Base ROUNDS_COUNT = 6 has_many :games_users, class_name: :GamesUsers has_many :users, through: :games_users has_many :rounds, inverse_of: :game end
#!/usr/bin/env ruby require 'fileutils' def go File.open(File.expand_path('nhl_to_rails.csv')) do |file| file.each_line do |line| l = line.split(';') p = Player.new p.nhl_rank = l[0] p.name = l[1] p.team = l[2] p.last_team = l[3] p.position = l[4] p.games = l...
require_relative "../test_helper" class OrderIsEmptyUponArrivalTest < Capybara::Rails::TestCase test "visiting Order upon arrival shows it is empty" do visit root_path within('.controls') do click_on "Order" end assert_content page, "Your Order is empty." end end
require "application_system_test_case" class CoordinatorsTest < ApplicationSystemTestCase setup do @coordinator = coordinators(:one) end test "visiting the index" do visit coordinators_url assert_selector "h1", text: "Coordinators" end test "creating a Coordinator" do visit coordinators_url...
module Monexa module Subscriber def self.create(data) Monexa::api_request :create_subscriber, wrap_account(data) end def self.update(data) Monexa::api_request :update_subscriber, wrap_account(data) end def self.delete(account_id) update(:account_information => {:account_id => a...
require 'rails_helper' RSpec.describe('Uploads', type: :request) do let(:user) { create(:user, :admin) } it('creates a upload and redirects to the edit page') do sign_in(user) get(new_upload_path) expect(response).to render_template(:new) attributes = { files: [test_file, test_file, test_file] } ...
json.reservations @reservations do |reservation| json.(reservation, :id, :classroom_id, :date, :title, :description, :from_block, :to_block) json.classroom_name reservation.classroom.name end
class AddThetasToExams < ActiveRecord::Migration def change add_column :exams, :thetas, :text end end